Trying to use sessionStorage in javascript - javascript

I'm trying to show a popup window only once per session. In order to achieve that I'm using sessionStorage function. however, the popup is showing up whenever I reload the web page. Can you please let me know where I'm making the mistake.
dialogue = new IMu.App.Dialogue();
dialogue.setHtmlMessage(IMu.string('dialogue-heading'));
dialogue.show({ showDetails: true });
window.sessionStorage.setItem('message','true');
var is_dialogue = window.sessionStorage.getItem('message');
if (is_dialogue != 'true')
{
dialogue.show();
}
Below is the show function
show: function(options, callback)
{
if (typeof(options) == 'function')
{
callback = options;
options = undefined;
}
var test = jQuery('body').children('div.imu-dialogue');
jQuery('body').children('div.imu-dialogue').remove();
var owner = self.owner = jQuery('body').child('div', 'imu-dialogue');
var box = owner.child('div', 'box');
var message = box.child('div', 'message');
if (this.message)
{
var value = this.message.value;
var method = this.message.type;
message[method](value);
}
if (self.details)
{
var details = box.child('div', 'details');
for (var i in self.details)
{
if (! self.details.hasOwnProperty(i))
continue;
var detail = details.child('div', 'detail');
var value = self.details[i].value;
var method = self.details[i].type || 'text';
detail[method](value);
}
var show = box.child('div', 'show-details');
if (! options || options.showDetails !== true)
{
show.text('Details');
details.hide();
}
else
{
details.show();
show.text('I agree');
}
show.on('click', function()
{
self.owner.remove();
});
}

You've got your logic backwards. You need to check if the sessionStorage item has been set first. If it has not been set, show the dialog and then set it.
if (!sessionStorage.getItem('notified')) {
let dialogue = new IMu.App.Dialogue();
dialogue.setHtmlMessage(IMu.string('dialogue-heading'));
dialogue.show({ showDetails: true });
sessionStorage.setItem('notified', 'true');
}
There is no need to check the value of the stored property. Simply testing for it's existence is enough.

Forget the dialogue.show();
If you try in a new tab of your browser the following code:
window.sessionStorage.setItem('message','true');
is_dialogue = window.sessionStorage.getItem('message');
is_dialogue != 'true' // false
refresh the page and run
is_dialogue = window.sessionStorage.getItem('message');
is_dialogue != 'true' // false
You may have something in your code whick clean session storage on mounted or on created ?

Related

JavaScript - Issues recovering a map in an object after being saved in localStorage

I've been dealing with this for some time. I've a list of sections in which the user checks some checkboxes and that is sent to the server via AJAX. However, since the user can return to previous sections, I'm using some objects of mine to store some things the user has done (if he/she already finished working in that section, which checkboxes checked, etc). I'm doing this to not overload the database and only send new requests to store information if the user effectively changes a previous checkbox, not if he just starts clicking "Save" randomly. I'm using objects to see the sections of the page, and storing the previous state of the checkboxes in a Map. Here's my "supervisor":
function Supervisor(id) {
this.id = id;
this.verif = null;
this.selections = new Map();
var children = $("#ContentPlaceHolder1_checkboxes_div_" + id).children().length;
for (var i = 0; i < children; i++) {
if (i % 2 == 0) {
var checkbox = $("#ContentPlaceHolder1_checkboxes_div_" + id).children()[i];
var idCheck = checkbox.id.split("_")[2];
this.selections.set(idCheck, false);
}
}
console.log("Length " + this.selections.size);
this.change = false;
}
The console.log gives me the expected output, so I assume my Map is created and initialized correctly. Since the session of the user can expire before he finishes his work, or he can close his browser by accident, I'm storing this object using local storage, so I can change the page accordingly to what he has done should anything happen. Here are my functions:
function setObj(id, supervisor) {
localStorage.setItem(id, JSON.stringify(supervisor));
}
function getObj(key) {
var supervisor = JSON.parse(localStorage.getItem(key));
return supervisor;
}
So, I'm trying to add to the record whenever an user clicks in a checkbox. And this is where the problem happens. Here's the function:
function checkboxClicked(idCbx) {
var idSection = $("#ContentPlaceHolder1_hdnActualField").val();
var supervisor = getObj(idSection);
console.log(typeof (supervisor)); //Returns object, everythings fine
console.log(typeof (supervisor.change)); //Returns boolean
supervisor.change = true;
var idCheck = idCbx.split("_")[2]; //I just want a part of the name
console.log(typeof(supervisor.selections)); //Prints object
console.log("Length " + supervisor.selections.size); //Undefined!
supervisor.selections.set(idCheck, true); //Error! Note: The true is just for testing purposes
setObj(idSection, supervisor);
}
What am I doing wrong? Thanks!
Please look at this example, I removed the jquery id discovery for clarity. You'll need to adapt this to meet your needs but it should get you mostly there.
const mapToJSON = (map) => [...map];
const mapFromJSON = (json) => new Map(json);
function Supervisor(id) {
this.id = id;
this.verif = null;
this.selections = new Map();
this.change = false;
this.selections.set('blah', 'hello');
}
Supervisor.from = function (data) {
const id = data.id;
const supervisor = new Supervisor(id);
supervisor.verif = data.verif;
supervisor.selections = new Map(data.selections);
return supervisor;
};
Supervisor.prototype.toJSON = function() {
return {
id: this.id,
verif: this.verif,
selections: mapToJSON(this.selections)
}
}
const expected = new Supervisor(1);
console.log(expected);
const json = JSON.stringify(expected);
const actual = Supervisor.from(JSON.parse(json));
console.log(actual);
If you cant use the spread operation in 'mapToJSON' you could loop and push.
const mapToJSON = (map) => {
const result = [];
for (let entry of map.entries()) {
result.push(entry);
}
return result;
}
Really the only thing id change is have the constructor do less, just accept values, assign with minimal fiddling, and have a factory query the dom and populate the constructor with values. Maybe something like fromDOM() or something. This will make Supervisor more flexible and easier to test.
function Supervisor(options) {
this.id = options.id;
this.verif = null;
this.selections = options.selections || new Map();
this.change = false;
}
Supervisor.fromDOM = function(id) {
const selections = new Map();
const children = $("#ContentPlaceHolder1_checkboxes_div_" + id).children();
for (var i = 0; i < children.length; i++) {
if (i % 2 == 0) {
var checkbox = children[i];
var idCheck = checkbox.id.split("_")[2];
selections.set(idCheck, false);
}
}
return new Supervisor({ id: id, selections: selections });
};
console.log(Supervisor.fromDOM(2));
You can keep going and have another method that tries to parse a Supervisor from localStorageand default to the dom based factory if the localStorage one returns null.

Why is my localstorage not keeping the variable's value after refresh?

So I have some code that I want to keep a certain variable's value after I go on to another page and when I come back to the original page and press a certain button it increases it value and it keeps the increades value. The problem is that the code doesn't seem to work as intended. The default value of the variable is 0, on button press it is increased with 2 and saved using the localstorage and I'm sent to my other page and then when I go back to the original page and press the same button again the variable is again 2. Why is that?
Here's my code:
$(document).ready(function()
{
var isShoes = false
var isShirt = false
var oneMoreShoe = false
var buttonClicked = 0;
$('#purchaseShoes').on('click', function()
{
buttonClicked+=2;
var Shoes = localStorage.setItem('img_shoes', '/static/Images/Sneakers.png')
var clicksCounter = localStorage.setItem('buttonClicked', JSON.stringify(buttonClicked))
var retainClicksCount = localStorage.getItem('buttonClicked')
var actualClickCount = JSON.parse(retainClicksCount)
isShoes = localStorage.setItem('isShoes', true)
alert(retainClicksCount)
if(retainClicksCount>= 4){
oneMoreShoe = localStorage.setItem('oneMoreShoe', true)
}
})
})
$(document).ready(function()
{
var isShoes = false
var isShirt = false
var oneMoreShoe = false
var buttonClicked = 0;
if (localStorage.getItem('buttonClicked')) // check if button click exists in storage and assign it to your variable
{
buttonClicked = localStorage.getItem('buttonClicked');
}
$('#purchaseShoes').on('click', function()
{
buttonClicked+=2;
var Shoes = localStorage.setItem('img_shoes', '/static/Images/Sneakers.png')
var clicksCounter = localStorage.setItem('buttonClicked', JSON.stringify(buttonClicked))
var retainClicksCount = localStorage.getItem('buttonClicked')
var actualClickCount = JSON.parse(retainClicksCount)
isShoes = localStorage.setItem('isShoes', true)
alert(retainClicksCount)
if(retainClicksCount>= 4){
oneMoreShoe = localStorage.setItem('oneMoreShoe', true)
}
})
})
Each time you update your page your buttonClicked variable becomes = 0. You need to check if local variable exists,if it's so you get value for your script variable from localstorage and then you add 2 and work with it.

Call functions from sources directly in Chrome console?

For a website there is this function under sources with the code:
betSlipView.prototype.stakeOnKeyUp = function(_key) {
var model = ob.slip.getModel(),
defval = ob.cfg.default_bet_amount;
selector = toJqId(["#stake-", _key].join('')),
stake_box = $(selector),
spl = stake_box.val();
if(spl != defval) {
spl = ob.slip.cleanFormatedAmount(spl);
if(spl === '' || isNaN(spl)) {
spl = 0;
$(selector).val('');
}
model.setBetStake(_key, spl);
$(toJqId(['#ob-slip-estimate-', _key].join(''))).html(
model.getBet(_key, 'pretty_returns')
);
} else {
$(selector).val(defval);
model.setBetStake(_key, defval);
$(toJqId(['#ob-slip-estimate-', _key].join(''))).html(
model.getBet(_key, 'pretty_returns')
);
}
//Update bonus amount
try {
var offers = model.getBet(_key, 'offers');
}
catch(err) {
var offers = "";
}
if(offers !== "" && typeof offers['STLWIN'] !== "undefined") {
this._handleAccumulatorBonusElements(_key, offers['STLWIN']);
};
// potential returns for this bet
this.updateTotals();
};
I cannot figure out how to (if possible) call this function directly from the console. Firstly, when I try to write betSlipView in the console, it cannot be found. Consequently if I copy the code to the console to define the function, betSlipView is still not found and if I try to change the function name, there are some names in the function body that cannot be found either. I wish to call this function with certain arguments, is this possible?
The whole code can be found here https://obstatic1.danskespil.dk/static/compressed/js/ob/slip/crunched.pkg.js?ver=0305f181cb96b61490e0fd2adafa3a91

One local storage JavaScript for fields on different pages

Three different web pages have three contenteditable areas each (content1, content2, and content3).
Each page links to one JavaScript which uses local storage to store the user's input and present it again on their return.
When I change the content on one page, it changes the content in the same editable area all three pages.
I want each page to be able to use the same script to save it's own data independently of the other pages.
I've tried adding page location (url) to the local storage key, to get each page to use the same script to store and retrieve it's own data, but I can't get it to work. Am new to JavaScript - would be grateful for any help. Thanks!
window.addEventListener('load', onLoad);
function onLoad() {
checkEdits();
}
// Get page location
var loc = encodeURIComponent(window.location.href);
// Add location to local storage key
function checkEdits() {
if (localStorage.userEdits1 != null) {
var userEdits1 = (loc + userEdits1);
document.getElementById('content1').innerHTML = localStorage.userEdits1;
}
if (localStorage.userEdits2 != null) {
var userEdits2 = (loc + userEdits2);
document.getElementById('content2').innerHTML = localStorage.userEdits2;
}
if (localStorage.userEdits3 != null) {
var userEdits3 = (loc + userEdits3);
document.getElementById('content3').innerHTML = localStorage.userEdits3;
}
};
document.onkeyup = function (e) {
e = e || window.event;
console.log(e.keyCode);
saveEdits();
};
function saveEdits() {
// Get editable elements
var editElem1 = document.getElementById('content1');
var editElem2 = document.getElementById('content2');
var editElem3 = document.getElementById('content3');
// Get edited elements contents
var userVersion1 = editElem1.innerHTML;
var userVersion2 = editElem2.innerHTML;
var userVersion3 = editElem3.innerHTML;
// Add page location to storage key
var userEdits1 = (loc + userEdits1);
var userEdits2 = (loc + userEdits2);
var userEdits3 = (loc + userEdits3);
// Save the content to local storage
localStorage.userEdits1 = userVersion1;
localStorage.userEdits2 = userVersion2;
localStorage.userEdits3 = userVersion3;
};
function clearLocal() {
if (confirm('Are you sure you want to clear your notes on this page?')) {
localStorage.setItem("userEdits1", "");
localStorage.setItem("userEdits2", "");
localStorage.setItem("userEdits3", "");
document.getElementById('content1').innerHTML = "";
document.getElementById('content2').innerHTML = "";
document.getElementById('content3').innerHTML = "";
alert('Notes cleared');
}
}
The actual problem of your script is this:
localStorage.userEdits1
To access the property of an object with a string (e.g. stored in a variable) you have to use the bracket notation:
locationStorage[userEdits1]
But I would propose a slightly more generic (and, imho, cleaner) solution...
Store the content of the editable elements in an object
var cache = {
<elementX id>: <content>,
<elementY id>: <content>,
<elementZ id>: <content>,
...
};
And then store this "cache" in the local storage with a page-specific key
localStorage.setItem(window.location.pathName, JSON.stringify(cache));
A possible implementation could be:
window.addEventListener('load', checkEdits);
getContentEditables().forEach(function(editable) {
// This prevents the function to execute on every keyup event
// Instead it will only be executed 100ms after the last keyup
var debouncedFunc = debounce(100, function(e) {
saveEdits();
});
editable.addEventListener("keyup", debouncedFunc);
});
function checkEdits() {
var cache = localStorage.getItem(window.location.pathName);
if (cache !== null) {
cache = JSON.parse(cache);
Object.keys(cache)
.forEach(function(key) {
var element = document.getElementById(key);
if (element !== null) {
element.innerHTML = cache[key];
}
});
}
}
function saveEdits() {
var cache = {};
getContentEditables().forEach(function(element) {
cache[element.id] = element.innerHTML;
});
localStorage.setItem(window.location.pathName, JSON.stringify(cache));
};
function clearLocal() {
if (confirm('Are you sure you want to clear your notes on this page?')) {
localStorage.removeItem(window.location.pathName);
getContentEditables().forEach(function(element) {
element.innerHTML = "";
});
alert('Notes cleared');
}
}
// helper
function getContentEditables() {
var elements = [];
document.querySelectorAll("[contenteditable]")
.forEach(function(element) {
if (element.id) {
elements.push(element);
}
});
return elements;
}
function debounce(timeout, func) {
var timeoutId;
return function() {
var that = this,
args = arguments;
clearTimeout(timeoutId);
timeoutId = setTimeout(function() {
func.apply(that, args);
}, timeout);
}
}
Use
localStorage[userEdits1]
Instead of
localStorage.userEdits1

why my alert shows undefined in javascript

var database = require('../../db');
var rightponame = '1';
var rightdevname = '';
var rightpopassword = '';
var rightdevpassword = '';
database.db.once('open', function() {
console.log('success');
var cursor = database.db.collection('user').find({}, {
_id: 0
});
cursor.each(function(err, doc) {
if (doc != null) {
rightponame = doc.productOwner;
rightdevname = doc.developer;
rightpopassword = doc.popassword;
rightdevpassword = doc.devpassword;
console.log(rightponame);
console.log(rightdevname);
console.log(rightpopassword);
console.log(rightdevpassword);
} else {
console.log('o');
}
});
});
function login() {
var getusername = document.getElementById("username").value;
var getpassword = document.getElementById("password").value;
alert(rightponame);
}
Finally, I get rightponame, rightdevname, rightpopassword and rightdevpassword value. But in the login function, I get undefined in the alert.
Why?
In JavaScript, alert is only available in the browser. It appears you're using node.js or the like. Try console.log instead, as you're doing on db open.
Then when you check the terminal window where the process is running, you should see the value of console.log.
Since console.log takes multiple values, it's helpful to prefix with something distinguishable like:
console.log('<<<<<<<', rightponame)

Categories

Resources