Why is storage not persisting? - javascript

I am having a simple problem where I set some test data to local storage after an event listener event.
<script>
document.getElementsByTagName("form")[0].setAttribute("action", "https://www.google.com/");
document.getElementsByTagName('form')[0].addEventListener('submit',
function(){
alert("Test");
localStorage.setItem("persondetails","person");
});
</script>
My problem is:
It adds the dat to session storage on the page that I am currently on but when I navigate to a new page it does not persist.
What am I missing?

What you miss is what SessionStorage is. From mdn:
The sessionStorage property allows you to access a session Storage
object for the current origin. sessionStorage is similar to
localStorage; the only difference is while data stored in localStorage
has no expiration time, 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 window will cause a new session to be initiated
with the value of the top-level browsing context, which differs from
how session cookies work.
Consider using localStorage instead. It will persist on new tabs and reloads

Related

How to detect if sessionStorage is going to die?

Obviously, we are able to store user data in sessionStorage.
Also, we can watch changes to sessionStorage:
window.addEventListener('storage', function(e) {
But what if we are also, for example, sending some info to our db and we need to do some important actions when user is done with our website, and he is closing all opened browser tabs of our website, and sessionStorage is about to die?
There is the event onbeforeunload, but it doesn't fit our issue, because many tabs of the same website can be open at once, and we cant be sure it is the last one.
So question is - can we detect when sessionStorage is about to die?
The goal is to detect when the last tab accessing a specific site is closing.
Assuming each tab is associated with a unique session ID, the following method should work:
Upon page load:
obtain session ID
retrieve array of active session IDs from localStorage
if session ID is not present in array, add it
store array to localStorage
Upon page unload:
retrieve array of active session IDs from localStorage
find and remove current session ID from array
update array to localStorage
if array is empty, perform your "last tab closing" action
What About Browser Crashes?
This scheme doesn't handle when a browser crashes. In that case, the page unload will never be detected, and localStorage will never have its array of active session IDs cleared.
One way to accommodate a crash is to set a timestamp with each session ID stored, then remove old session IDs.
let sessionArr = [
{ sessionId, timestamp },
...
]

How to differentiate browser close and refresh using angularjs?

I have localstorage for employeeid stored.When i refresh the browser get local storage value like employeeid based on employeeid get some data .when i close the browser i want to clear employeeid in local storage by using angularjs or javascript. I tried the following code.
window.onunload = close;
function close() {
//// do something...
localStorage.clear();
return null;
}
In the above code when i refresh the browser that time also window.onunload fired and clear the local storage values, but i want to clear local storage at the time of browser close only.
If you do not need this to work across different windows/tabs, then you should use sessionStorage instead of localStorage.
Where what you store into localStorage is “permanent”, sessionStorage stores values only until the window/tab is closed, similar to a “session cookie”, that is set without any lifetime – that will live only until the browser is closed (but will be available across different tabs when your site is open in more than one.)
A few more details can be found in these questions:
What is the difference between localStorage, sessionStorage, session and cookies?
HTML5 Local storage vs. Session storage
Maybe that's you're looking for Identifying Between Refresh And Close Browser Actions

Token not getting saved in $window.sessionStorage when page is opened in different browser

I'm initializing the token that is generated after I log in to my application in $window.sessioStorage .
var token = this.$window.sessionStorage["apiKey"];
But this token seem to be undefined when I copy the url(after log in ) and open in different browser.I'm redirected back to the login page.
Does $window.sessionStorage holds the values of variables in the same browser window?Or what could be another way to retain the value of token even if I opened the page in different browser window?
That's the right behaviour
The sessionStorage property allows you to access a session Storage
object. sessionStorage is similar to 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 window
will cause a new session to be initiated.
You can keep information even if the browser is closed and reopend another time by using localStorage, but, as I said, if you open other browser you'll have to set items agains.
Local storage examples here
Code example :
// set something in localStorage
localStorage.setItem('bgcolor', 'green');
// get something from localStorage
localStorage.getItem('bgcolor') // it will output green

keep global variables alive after resfresh, javascript

Scenario:
Let's say we have and app which works like:
Header
Content
footer
Header and Footer are statics and content is a div which is called via ajax to load an specific view.
So basically, our first view is login, after calling a login controlling, we get a list and move across the app w/o changing the link structure cause the ajax div content calling.
Problem:
When we refresh, we go back to the login page instead of the main view, which displays all the options which comes with the login controller answer. I'm trying to keep those options into a global variable, however after refreshing, all data is erased and there is not way I can go back to the main view even if session is alive (by session cookie), I only can back if I send the user and pw again, which I cannot. Eventually, storing the user and pw into cookies is not an option.
Any advise to solve this issue?
You can use DOM Storage to store the value of your global variables between reloads.
DOM Storage is a client side key/value storage.
localStorage.setItem('key', value);
value = localStorage.getItem('key');
There are two variants:
sessionStorage, this will store the value for the time of the users session
localStorage, this will keep the data between sessions
If you have to support ancient browsers you can use cookies to store values between reloads.

Storing JavasScript settings locally

With HTML5 and local storage, can JavaScript be used to save the state of a web page?
For example, some sites have increase font size buttons that are most likely controlled with JS. How can the property be saved so that on a refresh the size stays the same? Or is this done without JS?
Your best bet is probably to use localStorage, unless you do not want the settings to persist upon new sessions (you would use sessionStorage in that case). If you have multiple settings, you can store a serialized representation of your settings.
E.g.
var settings = {
fontSize: '11px',
otherConfig: 'test'
};
localStorage.setItem('settings', JSON.stringify(settings));
//then you can retrieve it
settings = JSON.parse(localStorage.getItem('settings'));
console.log(settings.fontSize); //11px
Note that if you want the settings to persist when users connects from multiple computers, you will have to use some server-side support.
Yes, it is done with Javascript. You can use
Cookies
Sessionstorage
This is a global object (sessionStorage) that maintains a storage area that's available for the duration of the page session. 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 window will cause a new session to be initiated.
Localstorage
localStorage is the same as sessionStorage with same same-origin rules applied but it is persistent.
The better/easier ones are sessionStorage and localStorage. The problem is that they aren't supported by old browsers.
Instead, dealing with cookies can be a nightmare, but they work on old browsers too.
Yes can save state to localStorage.
assume you have an object :
var settingsObj={
pageClass:'bigFont',
widgetSortOrder : [1,5,3,7]
}
You could save that whole object to one local storage key by stringifying the object. When page loads you would see if that key exists in localStorage and have your javascript do whatever it neds to with those settings
To stringify and store:
localStorage.setItem('mySettings', JSON.stringify(settingsObj) );
To retrieve from storage and convert to js object
var settings=JSON.parse(localStorage.getItem('mySettings'));

Categories