JavaScript: sessionStorage loses item - javascript

I have following JavaScript code in the Layout-Page of my ASP.NET MVC application to store a browser wide Id for an user as a cookie so I can access information in the session on server-side for the respective user.
if (sessionStorage.getItem("TestWindowId") == null) {
sessionStorage.setItem("TestWindowId", "#Guid.NewGuid().ToString("N")");
$.removeCookie("Test_Cookie");
storeWindowIdInBrowserWideCookie();
window.location=document.URL;
}
if ($.cookie("Test_Cookie") !== sessionStorage.getItem("TestWindowId")) {
$.removeCookie("Test_Cookie");
storeWindowIdInBrowserWideCookie();
window.location=document.URL;
}
function storeWindowIdInBrowserWideCookie() {
var cookieValue = sessionStorage.getItem("TestWindowId");
if (cookieValue != null) {
$.cookie("Test_Cookie", cookieValue);
}
}
In most cases this works.
But in some random cases for some users the sessionStorage.getItem("TestWindowId") returns null on the same browser tab it was definitely set before. In those cases I lose the Id and although the connection to the user information on server-side. According to my logs the sessionStorage item was set and in a callback call within the same second the sessionStorage of the same browser tab was null again.
What can cause the sessionStorage on client-side to lose items?
Or is there a error in my logic?
UPDATE:
There was a problem in my thinking pattern. The problem is not that the sessionStorage item was deleted but that the wrong cookie value was sent with the request to the server.
I opened another ticket since the question differs:
Store browser window specific id in cookie

As per the docs.
sessionStorage is similar to Window.localStorage, the only difference is while data stored in localStorage has no expiration set, data stored in sessionStorage gets cleared when the page session ends. A page session lasts for as long as the browser is open and survives over page reloads and restores. Opening a page in a new tab or closing window will cause session storage to expires.
So it may happen that client has closed the browser or open it in a new tab.

Related

Javascript cookie removed after leaving page

I'm attempting to create a cookie the first time a user visits a page on the website and store the pathname as the value of the cookie for that page for records.
I'm attempting on doing this by creating a function at the page load called GenerateCookie.
This function then checks to see if the cookie reportingpage exists or not and if it does not exist create the cookie. I would like the value to remain the same until the session is over. I am attempting to record the first page visited. So for example, if a user visits /testing-page/ I would like the cookie value to remain /testing-page/ even if they back out of the page and visit other pages, since that was the first page visited.
Currently, the cookie is created as expected with the pathname value as expected, but any time I back out of the page and visit a new page the cookie is then removed and set with the other pages pathname value. I've attempted to fix this issue by including the path= attribute when setting the cookie, but this has no effect.
How can I create a cookie and keep that same value for the entire session until the tab/browser is closed?
Here is a code snippet of my code:
GenerateCookie();
function GenerateCookie() {
// if cookie does not exist, create cookie reporting page
if (document.cookie.indexOf('reportingpage=') == -1) {
console.log('no cookie')
document.cookie = "reportingpage=https://www.testing.com" + window.location.pathname + "; path=/"
} else {
// if cookie exist, get value
console.log('cookie exist')
const name = "reportingpage"
const match = document.cookie.match(RegExp('(?:^|;\\s*)' + name + '=([^;]*)'));
console.log(match[1], 'value')
}
}
Storing a hundred cookies on someone's computer is really unethical, especially if it's for tracking their page visits. I'd be super annoyed if I visited a site and suddenly have a gazillion cookies to delete. But perhaps you have good reasons so if you really have to do it then use localStorage instead of cookies.
sessionStorage.setItem('someKey', window.location.pathname)

Do i have to use Session Storage or LocalStorage : javascript AWS

I have below scenario
Page 1 has a link, when user clicks on it, it gets navigated to portal page with page reload. So just before navigation, a JSON object is created
The size of this object comes around 4KB roughly.
Sample object
let obj = {
"date":"12/31/2018",
"year":"2019",
"zip":"93252",
"members":[
{
"sdf":true,
"age":21,
"fdssss":false,
"aaaa":false,
"fdss":null,
"fsdfsd":[
"ADULT"
]
},
{
"sdf":true,
"age":21,
"fdssss":false,
"aaaa":false,
"fdss":null,
"fsdfsd":[
"ADULT"
]
}
}
There is a back link from that portal page, on clicking page will be navigated back to Page 1 with a page reload.
So when the page is navigated back, I need the created JSON object back again. I need it only for that session or the data should be persistent even if the page is reloaded.
Do I have to use localStorage? If i store the object in localStorage, at what point i should clear the storage? How should I handle between different users?
Do I have to use sessionStorage? what will be the scope of the data availability
I'm using AWS service.
Q1:
you can have localStorage, and you should handle it at the code when first page loaded and you can delete it when user do signout or login, storage is about browser not user, if there are some users behind one computer at different times you must clear all data manually.
Q2:
you can also have sessionStorage, per tab and will be removed by closing browser.
in details:
This is depends on your scenario which means localStorage used for long time but sessionStorage used when you need to store something temporary.
but the important thing about sessionStorage is that it is exist per tab if you close tab and windows the sessionStorage completely removed, it used for critical data such as username and password whereas localStorage is used to shared data whole the browser.
localStorage has no expiration date, and it gets cleared only by code, or clearing the browser cache or locally stored data whereas sessionStorage object stores data only for a session, meaning that the data is stored until the browser (or tab) is closed.
at the end I suggest you to use localStorage because you may want to share that data whole the browser event after closing browser and you can store more data, in the other side there are limitation about them, when you are used storage you should handle them manually and take care.
suppose:
function removeStorage()
{
var obj = localStorage.getItem('obj');
if(obj !== null)
localStorage.removeItem('obj')
}
and in login or logout success action call removeStorage() and in Page1 load have something like below:
var obj = localStorage.getItem('obj');
if(obj !== null)
{
....
//show the obj in label or do what you want with it
...
}

HTML5 LocalStorage to maintain session across pages/tabs under same domain

Anyone provide me way, I can use HTML5 LocalStorage to use in Javascript to maintain session between server and client to keep track of session Timeout which will redirect the all tabs or pages in session Expired page.
Is there any way(Other than this) i can maintain session across the page/tabs under same domain to keep track of Session Timeout.
Thanks in Advance
You have not posted any code so the only think I can do for you is just show you a generic example which may not completely suit your requirement but will give an idea on how you could do it:
// show last settings pane if it's set
if ( localStorage.activePill ) {
$('.nav-pill-control > li').removeClass('active');
$('.nav-pill-control > li > a[href="' + localStorage.activePill + '"]').parent().addClass('active');
$('.nav-pill-pane').hide();
$(localStorage.activePill).show();
}
The sessionStorage object is equal to the localStorage object, except that it stores the data for only one session. The data is deleted when the user closes the specific browser tab.
In HTML5 you can use session to pass object from page to another:
// Save data to sessionStorage
sessionStorage.setItem('key', 'value');
// Get saved data from sessionStorage
var data = sessionStorage.getItem('key');
// Remove saved data from sessionStorage
sessionStorage.removeItem('key')
More Information

Cookie not being deleted after session closed

I'm using cookies that should be deleted after user closes the page, but they're not. This is how I set cookies with JS
document.cookie="status=false";
I can see the cookie in console and after I close browser and open it again and go to my webpage there's still cookie status=false any idea why?
I solved it with this "trick", I don't know why I can't get cookies to work
window.onbeforeunload = function() {
document.cookie="status=false";
};
document.cookie = ... sets individual cookie values, it does not set "the entire cookie" to the string you passed, so setting "status=false" simply binds or updates the "status" value, irrespective of whatever else is in the cookie:
document.cookie = "cow=bell";
document.cookie = "cat=lol";
// cookie is now "cow=bell&cat=lol", not just "cat=lol"
If you want to delete the entire cookie, set its expiration time to "in the past" and the browser will do the cleanup for you.
(As pointed out in a comment, if you never set an expiration timestamp for your cookie, it'l expire when the page session ends, e.g. you close the tab/browser)
I was actually doing this today. A great reference is the Mozilla cookie documents if you create a js with their var docCookies code then using the functions provided like docCookies.setItem() docCookies.setItem() docCookies.getItem() or docCookies.removeItem() work incredible well.

Data stored in localStorage isn't there when I redirect

I have Javascript on a page that sets localStorage data:
localStorage.setItem('blah', 1);
Then, I have code that will redirect to another page on a button click.
On the other page I try to access the item in localStorage, but I get Uncaught TypeError: Cannot read property 'blah' of null 30% of the time. How come localStorage isn't saving each time?
Am I missing something?
On Current Page
localStorage.setItem('blah', 1);
$('.btn').on('click', function() { window.location.href = 'http://example.com/signup?redirect=/chkout'; });
On Redirect Page
localStorage.getItem('blah', 1); ==> null
This might happen because
The tab/window is in incognito / private surfing mode
The browser is configured to track no history at all
The item was set on another port or scheme (of the same domain) (e.g. http://foo.com instead of https://foo.com)
From the W3C specification:
The user agent may throw a SecurityError exception and abort these steps instead of returning a Storage object if the request violates a policy decision (e.g. if the user agent is configured to not allow the page to persist data).
If the Document's origin is not a scheme/host/port tuple, then throw a SecurityError exception and abort these steps.
The localStorage data should persist, by several documentations. There may be a case when your localStorage data gets overwritten by some other operation. You can try to debug this by adding following eventListener:
window.addEventListener("storage", function(data) {
console.debug(data);
}, false);
This should log the data, every time the storage is accessed.

Categories