How do i auto-refresh my log rather then refreshing it manually - node.js

I currently have a log box which shows the log from my backend. I have a button to refresh the log and the latest set of logs shows up. How do I set it to a auto-refresh log?
I have the code below for the button and switchbox
<div class="form-group row m-b-10">
<label class="col-form-label">Auto-Refresh:</label>
<div class="col-md">
<div class="switcher switcher-success">
<input type="checkbox" v-model="checked" name="switcher_checkbox_2" id="switcher_checkbox_2" checked="true" value="1" v-on:change="toggle">
<label for="switcher_checkbox_2"></label>
</div>
<div class="switcher switcher-success">
<button v-if="!checked" #click="logNode(namespace)" class="btn btn-xs btn-success">Refresh</button>
</div>
</div>
And the function for the refresh button is below. How do I call a function for the log to load on auto refresh when the switchbox is on?
logNode(namespace) {
console.log(namespace)
this.hidemodal = true;
this.logShow = true;
var requestobj = {
Namespace: namespace,
};
var apiobj = {
tablename: "bnm",
Id: VueCookies.get("activeNetwork_Id"),
method: "post"
};
var obj = {
apiobj: apiobj,
mainobj: requestobj
};
this.$store
.dispatch("logsAPI", obj)
.then(response => {
console.log(response);
console.log("test result");
if (response.data || response.status == 200) {
this.logString = response.data.Logstr;
this.$notify({
group: "querynotify",
title: "Success",
type: "success",
position: "top-right",
text: "Sucessfully Created Logs " + ":\n" + response.data.Username
});
} else {
this.$notify({
group: "querynotify",
title: "Error",
type: "warn",
position: "top-right",
text: "Error Creating Logs " + ":\n" + response.data.Username
});
}
})
.catch(error => {
this.$notify({
group: "querynotify",
title: "Error",
type: "error",
position: "top-right",
text: "Error View this node Log" +
":\n" +
error.data.err +
":\n" +
error.data.details
});
});
},

When you check box is checked, you can use setInterval() and when your checkbox is unchecked clearInterval.
Please check below working snippet.
*Note in this snippet, I have just used simple log for demo purpose. In that demo you can put your logic.
new Vue({
el: '#app',
data: {
checked: false,
autoRef:null
},
methods: {
toggle() {
if(this.checked){
this.autoRef = setInterval(() => {
this.logNode('Auto refresh called');
}, 3000);
}else{
clearInterval(this.autoRef);
}
},
logNode(msg) {
console.log(msg)
}
}
});
.btn-success {
background: green;
padding: 10px;
border: 1px solid #ccc;
color: #fff;
}
<link href="https://cdn.jsdelivr.net/npm/vuetify#1.2.2/dist/vuetify.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vuetify#1.2.2/dist/vuetify.min.js"></script>
<div id="app" class="form-group row m-b-10">
<label class="col-form-label">Auto-Refresh:</label>
<div class="col-md">
<div class="switcher switcher-success">
<input type="checkbox" v-model="checked" name="switcher_checkbox_2" id="switcher_checkbox_2" checked="true" value="1" v-on:change="toggle">
<label for="switcher_checkbox_2"></label>
</div>
<div v-if="!checked" class="switcher switcher-success">
<button ref="myButton" #click="logNode('on button click')" class="btn btn-xs btn-success">Refresh</button>
</div>
</div>

Related

Can't perform a React state update on an unmounted component, I tried to fix it but it still renders the same problem

Hi there I am using Chart.js to create a doughnut chart, but I see to get "Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function." I will show my front end and back end that are relevant to the question. Also the server side fetches everything correctly and it also console logs it perfectly in the front end the way I need it to.
results. js basically the server side
router.get("/occ", authorization, async (req, res) => {
try {
console.log(req);
const result = await pool.query(
// "SELECT occupation,COUNT(occupation) FROM resources GROUP BY occupation;",
"SELECT occupation,COUNT(occupation) as values FROM resources GROUP BY occupation"
);
console.log(req);
console.log(result);
res.status(200).json({
status: "success",
data: {
occupationResults: result.rows, //this gets the one row we need
},
});
} catch (err) {
console.error(err.message);
}
});
DoughnutChart.js the component itself
import React, { Fragment, useState, useEffect } from "react";
import { Chart as ChartJS, ArcElement, Tooltip, Legend } from "chart.js";
import { Doughnut } from "react-chartjs-2";
ChartJS.register(ArcElement, Tooltip, Legend);
const DoughnutChart = () => {
// const [user_id, setuserid] = useState("");
const [results, setResults] = useState([]);
async function getResults() {
try {
const response = await fetch(`http://localhost:4001/results/occ`, {
method: "GET",
//pass token with localstorage because it is stored in the header
headers: { token: localStorage.token },
});
const parseRes = await response.json();
// setpersonalForm(parseData);
console.log(parseRes);
// setUsername(parseRes.username);
setResults(parseRes.data.occupationResults);
// setuserid(parseRes.user_id); //
// const encryptStorage = new EncryptStorage('secret-key');
// removed the localstorage user id
console.log(parseRes.data.occupationResults);
} catch (err) {
console.error(err.message);
}
}
var data = {
labels: results?.map((x) => x.occupation),
datasets: [
{
label: `${results?.length} Amount per Occupation`,
data: results?.map((x) => x.values),
backgroundColor: [
"rgba(255, 99, 132, 0.2)",
"rgba(54, 162, 235, 0.2)",
"rgba(255, 206, 86, 0.2)",
"rgba(75, 192, 192, 0.2)",
"rgba(153, 102, 255, 0.2)",
"rgba(255, 159, 64, 0.2)",
],
borderColor: [
"rgba(255, 99, 132, 1)",
"rgba(54, 162, 235, 1)",
"rgba(255, 206, 86, 1)",
"rgba(75, 192, 192, 1)",
"rgba(153, 102, 255, 1)",
"rgba(255, 159, 64, 1)",
],
borderWidth: 1,
},
],
};
var options = {
maintainAspectRatio: false,
scales: {
y: {
beginAtZero: true,
},
},
legend: {
labels: {
fontSize: 26,
},
},
};
//going to make a request when we get to this component, this is for getting from database
useEffect(() => {
getResults();
return () => {
setResults({}); // I added this but it still doesn't work
};
}, []);
return (
<div>
<Doughnut data={data} options={options} height={400} />
</div>
);
};
export default DoughnutChart;
Where I am importing the component.
import React, { Fragment, useState, useEffect } from "react";
import DoughnutChart from "./DoughnutChart";
//import { toast } from "react-toastify";
import "./pagecss/home.css";
// import { FontAwesomeIcon } from "#fontawesome-free-solid";
// import { encryptStorage } from "./encrypt";
const Home = ({ setAuth }) => {
const [username, setUsername] = useState("");
const [user_id, setuserid] = useState("");
// const [personalForm, setpersonalForm] = useState([]);//
// const [Pform, setform] = useState(false);
async function getUsername() {
try {
const response = await fetch("http://localhost:4001/home/", {
method: "GET",
//pass token with localstorage because it is stored in the header
headers: { token: localStorage.token },
});
const parseRes = await response.json();
// setpersonalForm(parseData);
setUsername(parseRes.username);
setuserid(parseRes.user_id); //
// const encryptStorage = new EncryptStorage('secret-key');
// encryptStorage.setItem("user_id", parseRes.user_id);
console.log(parseRes);
} catch (err) {
console.error(err.message);
}
}
//going to make a request when we get to this component, this is for getting from database
useEffect(() => {
getUsername();
}, []);
return (
<Fragment>
<div className="container">
<div className="row">
<div className="col-md-4 col-sm-12 d-flex justify-content-center">
<div className="card-body text-center text-white">
<i className="fa-solid fa-bullseye fa-6x my-3 "></i>
<h2 className="card-title mb-4">Card Title</h2>
<p className="card-text">
Our Mission is to help the community out by helping people with
mental health issues
</p>
</div>
</div>
<div className="col-md-4 col-sm-12 d-flex justify-content-center">
<div className="card-body text-center text-white">
<i className="fa-solid fa-glasses fa-6x text-center my-3 "></i>
<h2 className="card-title mb-4">Card Title</h2>
<p className="card-text">
Our Mission is to help the community out by helping people with
mental health issues
</p>
</div>
</div>
<div className="col-md-4 col-sm-12 d-flex justify-content-center">
<div className="card-body text-center text-white pb-4">
<i className="fa-solid fa-hand-holding-medical fa-6x text-center my-3 "></i>
<h2 className="card-title mb-4">Card Title</h2>
<p className="card-text">
Our Mission is to help the community out by helping people with
mental health issues
</p>
</div>
</div>
</div>
</div>
<div className="container-fluid">
<div className="row justify-content-around">
<div
className="card col-lg-5 col-md-6 col-sm-12 d-flex justify-content-center mb-5 "
id="CardOne"
>
<img
src={require("./pictures/ProPic.jpg")}
className="card-img-top"
id="pictureOne"
alt="..."
/>
<div className="card-body text-center text-black">
<h2 className="card-title mb-4">Alexey Aulov</h2>
<p className="card-text">
Hi my name is Alexey Aulov I am a senior at College of Staten
Island studying Information System and Informatics. I had the
original idea of Essential Health after I witnessed that
sometimes the best way for people to get mental help is to have
Therapist that can relate to you as much as possible to help you
out. Helping people gives me the most gratitude in life.
</p>
</div>
</div>
<div
className="card col-lg-5 col-md-6 col-sm-12 d-flex justify-content-center mb-5 "
id="CardTwo"
>
<img
src={require("./pictures/ProPic.jpg")}
className="card-img-top"
alt="..."
id="pictureTwo"
/>
<div className="card-body text-center text-black">
<h2 className="card-title mb-4">Card Title</h2>
<p className="card-text">
Our Mission is to help the community out by helping people with
mental health issues
</p>
</div>
</div>
</div>
<DoughnutChart />
</div>
</Fragment>
);
};
export default Home;

Croppie and NodeJS : Upload resized images

I'm trying to upload squared images for my ecommerce app.
I want all my images to be square for products images.
I'm using croppie Js, Expressjs and ejs.
Here is my actual code :
<label>Image</label>
<div id="modal">
<a class="button actionUpload">
<input class="from-control" type="file" id="upload" value="Choose Image" name="image" accept="image/*">
</div>
</a>
<div id="main-cropper"></div>
<button class="actionDone">Done</button>
And my JavaScript
var basic = $('#main-cropper').croppie({
viewport: {
width: 200,
height: 200
},
boundary: {
width: 300,
height: 300
},
showZoomer: true,
url: '/images/logo_AR.png'
});
basic.hide()
function readFile(input) {
if (input.files && input.files[0]) {
basic.show()
var reader = new FileReader();
reader.onload = function (e) {
$('#main-cropper').croppie('bind', {
url: e.target.result
});
$('.actionDone').toggle();
$('.actionUpload').toggle();
}
reader.readAsDataURL(input.files[0]);
}
}
$('.actionUpload input').on('change', function () {
readFile(this);
});
$('.actionDone').on('click', function () {
$('.actionDone').toggle();
$('.actionUpload').toggle();
})
When I upload the image on AWS using multer on my rooter, the crop doesnt work and the images isn't modified...

PayloadTooLargeError: request entity too large when upload image

I am trying to upload/and save an image in base64 format to my mongo database.
If I use a very very small image it works, but I try to use an image of 161 kb, I have this error:
PayloadTooLargeError: request entity too large
So I try to convert my image with Json but I got an error or it doesn't work,
Her my code ( I am using vue):
<template>
<div class="profile">
<div class="px-4">
<div class="row justify-content-center">
<div class="col-lg-3 order-lg-2">
<div class="card-profile-image image-preview">
<div v-if="profImage !=undefined && profImage.length > 0">
<a>
<img
:src="profImage"
class="rounded-circle"
/>
</a>
</div>
<div>
<div class="file-upload-form">
Upload image:
<input
type="file"
#change="previewImage"
accept="image/*"
/>
</div>
<div class="image-preview" v-if="imageData.length > 0">
<img class="preview" :src="imageData" />
<button #click="updateUserImage"></button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
Here my js file:
<script>
import DataService from '#/services/DataService'
export default {
name: 'Profile',
data: function() {
return {
username: '',
imageData: '',
profImage: '',
}
},
methods: {
previewImage: function(event) {
var input = event.target
if (input.files && input.files[0]) {
var reader = new FileReader()
reader.onload = e => {
this.imageData = e.target.result
}
reader.readAsDataURL(input.files[0])
}
},
async getAllInfo() {
var userImage = await DataService.getUserImage({
username: this.username
})
this.profImage = userInfo.data.user[0].profImage //IT Works
this.profImage = JSON.parse(userInfo.data.user[0].profImage) //I get an error
},
async updateUserImage() {
var temp = JSON.stringify(this.imageData)
console.log(this.firstname)
await DataService.updateUserInfo({
username: this.username,
user: {
profImage: temp
}
})
}
},
mounted() {}
}
</script>
When I try to use "JSON.parse(userInfo.data.user[0].profImage)"I get an error :
"Unexpected token d in JSON at position 0"
I also try with JSON.Stringify, but I get is not a function.
In my db, the image is saved in this way:
profImage: {
image: Buffer,
require: false
},
What am I doing wrong? I am using mongodb, vue , express and node.
I change the parser limit using
bodyParser.json({ limit: "50mb" })
and works for me

How to send a large datauri of an image to express server

I have the daturi of an image which is uploaded from the desktop.I would like to send this data uri to express server so as to save the dataUri in a text file. Since the size of the data uri of the image is quite large I am getting payload too large error which is understandable. I tried using multer but I couldn't figure out how to extract the data uri of the image when multer is used, on the server side.Any help on this is greatly appreciated.
Below is some of the code sample that I am trying to use
<div class="row">
<div class="form-group">
<label class="btn btn-default btn-file" for="FileUpload">Upload a Plan</label>
<input type="file" id ="FileUpload" accept="image/*" capture="camera" value="" onchange="readFileURL(this);" style="display: none;">
<img id="chosenFile" src="#" style="visibility: hidden;"/>
</div>
</div>
<div class="row">
<div class="col-sm-12"><button style="background-color: green" class="btn btn-default btn-sm" onclick="handleUplod(this)">Upload</button></div>
</div>
<script type="text/javascript">
function readFileURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
document.getElementById("chosenFile").style.visibility="visible";
reader.onload = function (e) {
$('#chosenFile').attr('src', e.target.result).width(150).height(150);
console.log("result:",e.target.result);
imageData = e.target.result;
};
console.log("data url:"+reader.readAsDataURL(input.files[0]));
}
};
function handleUplod(){
$.ajax({
type: "POST",
url: "/send",
data: { MyPlanDataUri:imageData },
success: function(result){
location.href= "/someplace";
},
error: function(result) {
alert('error');
}
});
};
On the server side I am doing the following
app.post('/send', function(req,res) {
var Tex1 = req.body.MyPlanDataUri;
var newFile = "ImageFile.txt";
fs.writeFile(newFile, Tex1, (err) => {
if (err) res.send(err);
console.log('File saved successfully ! - ', newFile);
}
);
res.send("Successfull");
}
P.S the above code works perfectly fine for small datauri's

How to add action buttons in a popup and navigate to a website in chrome extension?

I am in need to a show 2 pop ups on 2 different situation.Presently I am checking a server file and storing its credentials in a localStorage.Each time when the user clicks on the extension,it should check if the localStorage is empty or not.If it is empty,then a pop up should be seen and asks for his username.this is stored in localstorage.Next time when the user clicks on the icon,the localstorage is not empty,so it should show another pop up showind a field for username with 2 buttons namely 'change settings' and 'go to website'.When the user clicks on change settings,again the popup shuuld appear asking user name.If he clicks go to website,it should navigate to a website.How can this be done?please help me.I have tried button the button is not working.And also the 2nd pop up is always shown only on reloading the extension.Please help me.
Here is my background.js
here is my updated popup.js
window.addEventListener('DOMContentLoaded', function() {
var divLoading = document.querySelector('div#loadingContainer');
var divSettings = document.querySelector('div#settingsContainer');
var divLoggedIn = document.querySelector('div#loggedInContainer');
var divChange = document.querySelector('div#settingsChange');
var user1 = divSettings.querySelector('input#user1');
var form = divSettings.querySelector('form#userinfo');
var user2 = divLoggedIn.querySelector('span#user2');
var change = divLoggedIn.querySelector('input#change');
var calpine = divLoggedIn.querySelector('input#calpine');
var user3 = divChange.querySelector('input#user3');
var form3 = divChange.querySelector('input#changeset');
var cancel = divChange.querySelector('input#emailcancel');
var user = localStorage.username;
if (user) {
// user1.value = user2.value = user;
user1.value = user2.textContent = user;
user3.value = user;
divLoggedIn.style.display = 'block';
divSettings.style.display = 'none';
divChange.style.display = 'none';
} else {
divSettings.style.display = 'block';
divChange.style.display = 'none';
divLoggedIn.style.display = 'none';
user1.focus();
user1.select();
}
divLoading.style.display = 'none';
form.addEventListener('submit', function(evt) {
evt.preventDefault();
var userStr = user1.value;
chrome.runtime.getBackgroundPage(function(bgPage) {
bgPage.login(userStr);
});
window.close();
});
form3.addEventListener('click', function() {
var userStr = user3.value;
chrome.runtime.getBackgroundPage(function(bgPage) {
bgPage.login(userStr);
});
window.close();
});
change.addEventListener('click', function(evt) {
divLoggedIn.style.display = 'none';
divSettings.style.display = 'none';
divChange.style.display = 'block';
user3.focus();
user3.select();
});
cancel.addEventListener('click', function() {
divLoggedIn.style.display = 'block';
divSettings.style.display = 'none';
divChange.style.display = 'none';
user3.focus();
user3.select();
});
calpine.addEventListener('click', function() {
chrome.tabs.create({ url: 'http://www.calpinemate.com/' });
});
});
I have made some changed as i was asked to do so.I have added a new div named divchange.
here is my updated userinfo.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="popbak.js"></script>
</head>
<body>
<div id="loadingContainer"></div>
<div id="settingsContainer">
<b>Please Enter your Email ID/Employee Code</b>
<br />
<br />
<form id="userinfo">
<table>
<tr><td> <label for="user">Email/Employee Code:</label></td>
<td> <input type="text" id="user1" required /></td></tr>
<tr><td> <input type="submit" id="login" value="Log In" /></td></tr>
</table>
</form>
</div>
<div id="settingsChange">
<b>Please Enter your Email ID/Employee Code</b>
<br />
<br />
<table>
<tr><td><label for="user">Email/Employee Code:</label></td>
<td><input type="text" id="user3" required /></td></tr>
<tr><td><input type="button" id="emailchange" value="Change" /></td>
<td><input type="button" id="emailcancel" value="Cancel" /></td> </tr>
</table>
</div>
<div id="loggedInContainer">
<table>
<tr><td> <label for="user">Email/Employee Code:</label></td>
<!-- <input type="text" id="user2" readonly /> -->
<td><span id="user2"></span></td> </tr>
<br />
<tr><td><input type="button" id="calpine" value="Go to Calpinemate"/></td>
<td><input type="button" id="change" value="Change Settings"/></td></tr>
</table>
</div>
</body>
</html>
here is my bgpage.login()
function login(useremail){
if(!useremail)
{
alert('Please enter your Email/Employee code'); //this is not working
return;
}
var urlPrefix = 'http://www.calpinemate.com/employees/attendanceStatus/';
var urlSuffix = '/3';
var req1 = new XMLHttpRequest();
req1.addEventListener("readystatechange", function() {
if (req1.readyState == 4) {
if (req1.status == 200) {
var item=req1.responseText;
if(item==1){
localStorage.username=useremail;
updateIcon();
}
else
{
alert('Please enter a valid Email/employee code');
updateIcon();
}
}
else {
alert("ERROR: status code " + req1.status);
}
}
});
var url = urlPrefix + encodeURIComponent(useremail) + urlSuffix;
req1.open("GET", url);
req1.send(null);
}
Here is my background.js
var myNotificationID = null;
var oldChromeVersion = !chrome.runtime;
setInterval(function() {
updateIcon();
}, 1000);
function getGmailUrl() {
return "http://calpinemate.com/";
}
function isGmailUrl(url) {
return url.indexOf(getGmailUrl()) == 0;
}
function onInit() {
updateIcon();
if (!oldChromeVersion) {
chrome.alarms.create('watchdog',{periodInMinutes:5,delayInMinutes: 0});
}
}
function onAlarm(alarm) {
if (alarm && alarm.name == 'watchdog') {
onWatchdog();
}
else {
updateIcon();
}
function onWatchdog() {
chrome.alarms.get('refresh', function(alarm) {
if (alarm) {
console.log('Refresh alarm exists. Yay.');
}
else {
updateIcon();
}
});
}
if (oldChromeVersion) {
updateIcon();
onInit();
}
else {
chrome.runtime.onInstalled.addListener(onInit);
chrome.alarms.onAlarm.addListener(onAlarm);
}
function updateIcon(){
if(localStorage.username){
var urlPrefix = 'http://www.calpinemate.com/employees/attendanceStatus/';
var urlSuffix = '/2';
var req = new XMLHttpRequest();
req.addEventListener("readystatechange", function() {
if (req.readyState == 4) {
if (req.status == 200) {
var item=req.responseText;
if(item==1){
chrome.browserAction.setIcon({path:"calpine_logged_in.png"});
chrome.browserAction.setBadgeBackgroundColor({color:[190, 190, 190, 230]});
chrome.browserAction.setBadgeText({text:""});
chrome.notifications.clear('id1', function(){});
}
else{
chrome.browserAction.setIcon({path:"calpine_not_logged_in.png"});
chrome.browserAction.setBadgeBackgroundColor({color:[190, 190, 190, 230]});
chrome.browserAction.setBadgeText({text:""});
chrome.notifications.create(
'id1',{
type: 'basic',
iconUrl: '/calpine_not_logged_in.png',
title: 'Warning : Attendance',
message: 'Please mark your Attendance !',
buttons: [{ title: 'Mark',
iconUrl: '/tick.jpg'
},{ title: 'Ignore',
iconUrl: '/cross.jpg'}],
priority: 0},
function(id) { myNotificationID = id;}
);
}
}
else {
alert("ERROR: status code " + req.status);
}
}
});
var url = urlPrefix + encodeURIComponent(localStorage.username) + urlSuffix;
req.open("GET", url);
req.send(null);
}
}
onInit();
First of all, the localStorage of the background-page and that of the popup are not the same objects. Besides, each time the popup is shown, it is loaded anew, thus the localStorage is empty.
UPDATE: Thx to rsanchez's comment, I correct my mistake: the popup shares the localStorage object of the extension (which is the same as the one of the background-page).
You should use the localStorage of the background-page. (Keep in mind this works only because you have a persistent background-page !)
The simplest (and most reliable) way is to have a single popup with two different divs (one for entering credentials and one for logging in) and display only one at a time.
E.g.:
1) Remove any chrome.browserAction.onClicked... listener from the background-page (it won't hurt leaving it there as it will never be triggered, but it will confuse you in the future).
2) Declare a popup in your manifest (if you don't have already done do):
<pre>
...
"browser_action": {
...
"default_popup": "popup.html"
},
...
</pre>
3). Create a file named popup.html with the following code:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="popup.js"></script>
</head>
<body>
<div id="loadingContainer"><h3>Loading...</h3></div>
<div id="settingsContainer" style="display:none;">
<b>Enter your Email ID/Employee Code</b>
<br />
<br />
<form id="userinfo">
<label for="user">Email/Employee Code:</label>
<input type="text" id="user1" required />
<input type="submit" id="login" value="Log In" />
</form>
</div>
<div id="loggedInContainer" style="display:none;">
<label for="user">Email/Employee Code:</label>
<!--<input type="text" id="user2" readonly />-->
<span id="user2"></span>
<br />
<input type="button" id="calpine" value="Go to Calpinemate"/>
<input type="button" id="change" value="Change Settings"/>
</div>
</body>
</html>
</pre>
4) Create a file named popup.js with the following code:
window.addEventListener('DOMContentLoaded', function() {
/* Container divs */
var divLoading = document.querySelector('div#loadingContainer');
var divSettings = document.querySelector('div#settingsContainer');
var divLoggedIn = document.querySelector('div#loggedInContainer');
/* Settings-container fields */
var user1 = divSettings.querySelector('input#user1');
var form = divSettings.querySelector('form#userinfo');
/* LoggedIn-container fields */
//var user2 = divLoggedIn.querySelector('input#user2');
var user2 = divLoggedIn.querySelector('span#user2');
var change = divLoggedIn.querySelector('input#change');
var calpine = divLoggedIn.querySelector('input#calpine');
/* Query the extension's localStorage
* in order to decide which DIV to show */
var user = localStorage.username;
if (user) {
/* 'Username' is set: Show the LoggedIn-container
* (after updating the value of the (readonly) '#user' field) */
//user1.value = user2.value = user;
user1.value = user2.textContent = user;
divLoggedIn.style.display = 'block';
} else {
/* 'Username' is not set: Show the Settings-container */
divSettings.style.display = 'block';
user1.focus();
user1.select();
}
divLoading.style.display = 'none';
/* Listener for '#userinfo' form */
form.addEventListener('submit', function(evt) {
evt.preventDefault();
var userStr = user1.value;
chrome.runtime.getBackgroundPage(function(bgPage) {
bgPage.login(userStr);
});
window.close();
});
/* Listener for '#change' button */
change.addEventListener('click', function(evt) {
divLoggedIn.style.display = 'none';
divSettings.style.display = 'block';
user1.focus();
user1.select();
});
/* Listener for '#calpine' button */
calpine.addEventListener('click', function() {
chrome.tabs.create({ url: 'https://your.domain.goes/here' });
});
});

Resources