sessionStorage cleaned up unexpectedly on Android - javascript

I have a website which saves a stringified JavaScript object into the sessionStorage. It works well on desktop browsers - data survives over page reloads as per described on MDN.
On Android phones, it is not uncommon that a tab is reloaded when user switches back from another tab or when the browser is brought back from background to foreground, and I expect the sessionStorage will persist. This doesn't however seem to be the case. The sessionStorage is gone missing, as if a new session is created.
I have thought of using localStorage instead, which will not expire even if the session is closed. It doesn't really sort out all my problems though - as I expect a user can open it multiple times on multiple tabs, and do different things on each of them.
So my questions are:
Is the sessionStorage behavior described above as expected? If not, what can I do to rectify it?
If the behavior is as expected, and I have to rely on localStorage, how can I identify the object stored for each individual tab?
Thanks in advance for your help!

As others commented, SessionStorage is temporary by design. Mobile browser lifecycle is highly geared towards reducing resource usage and tabs are teardown more aggressively.
To workaround this issue, you can push a random tab ID to the URL and then prefix all LocalStorage keys with this ID. When tab is refreshed you simply read the tab ID from the URL and use it for accessing data in LocalStorage.
LocalStorage has a very simple API, so you could write a wrapper hiding the key prefixing away from your other code.

Yes, that is how sessionStorage works. The behavior is expected.
sessionStorage is unique per tab. If the user closes the tab the sessionStorage gets deleted.That is, the session storage is saved only as long as user stays on the tab.
Whatever you store in localStorage persists until explicitly deleted. Changes made are saved and available for all current and future visits to the site.
So, yes, it'd be better to use localStorage and clear it out at the end of the session.

Related

Clear local storage on closing all tabs or entire browser

How can I clear the local storage by closing all the tabs of the same domain (not closing one tab) or the entire browser? Session storage is not useful here as it cant share data with other tabs, so I haven't used session storage here. If I use event listeners like beforeunload, it is getting triggered even on page refresh, So what is the possible way to implement this concept in React?
Upon trying with taking count of tabs on loading and unloading, still, it is causing problems when there is one tab remaining. Can anyone please help me with an idea for this concept?
Use sessionStorage. There's a trick that involves writing token to localStorage that would tell the sessionStorage that there's shared data between tabs which can be retrieved using that token. See https://medium.com/#marciomariani/sharing-sessionstorage-between-tabs-5b6f42c6348c
I will try to paste some snippets from there, but really I don't know if that's allowed
You might want to look at the Broadcast Channel API
https://developer.mozilla.org/en-US/docs/Web/API/Broadcast_Channel_API
This API allow you to communicate between tabs, iframes, etc. sitting on the same origin.

When is sessionStorage actually cleared?

I have some javascript that checks for an object in sessionStorage, and uses it to refill an input field. I use this to help users on my site if they leave the form unfinished and either navigate away or try to submit the form after their session has expired.
My understanding is that sessionStorage is NOT linked to a server session, it is linked to the browser, so whether I have a new session on the server or not is irrelevent.
This was supported when I was testing this initially a few months ago. However, it seems to no longer be the case, and when I clear my session cookie and reload my page, my sessionStorage is also cleared out. This is using both Chrome and Firefox.
I don't want to use localStorage as that could cause issues with shared computers, whereas sessionStorage will be wiped out when the browser windows is closed.
JS to get the value of my stored object:
JSON.parse(sessionStorage.getItem("draftPost") || null);
JS to save the value:
$("#wallText").on("change", function(){
sessionStorage.setItem("draftPost", JSON.stringify(draftPost));
});
Session storage is cleared when the tab closes. It persists over page reloads and restores. See: https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage
Whenever a document is loaded in a particular tab in the browser, a unique page session gets created and assigned to that particular tab. That page session is valid only for that particular tab.
A page session lasts as long as the tab or the browser is open, and survives over page reloads and restores.
Opening a page in a new tab or window creates a new session with the value of the top-level browsing context, which differs from how session cookies work.
Opening multiple tabs/windows with the same URL creates sessionStorage for each tab/window.
Duplicating a tab copies the tab's sessionStorage into the new tab.
Closing a tab/window ends the session and clears objects in sessionStorage.
Note that the duplication of the tab does not seem to work in Firefox, it does however in Chrome.
Something to bear in mind with sessionstorage on mobile safari.
As stated by Archived version of the Window.sessionStorage docs on MDN dated 2018:
Note: since iOS 5.1, Safari Mobile stores localStorage[sic - possible misprint of sessionStorage] data in the cache folder, which is subject to occasional clean up, at the behest of the OS, typically if space is short.
This clean-up takes place all too frequently on mobile safari, and all sessionStorage variables are destroyed for all open tabs.
For example, having say 5 tabs open, and then loading a new page which has lots of javascript and css will cause the clean-up, destroying all sessionstorage variables.
However, localstorage variables are preserved.
Also, on safari, (i believe both desktop and mobile), in-private browsing will prevent using either localstorage or sessionstorage.
Two things might help you.
It is similar to localStorage.
The data is not persistent i.e. data is only available per window (or
tab in browsers like Chrome and Firefox). Data is only available during the page session. Changes made are saved and available for the
current page, as well as future visits to the site on the same
tab/window. Once the tab/window is closed, the data is delete
sessionStorage data is cleared when the session ends (hence the name, sessionStorage). Data in sessionStorage is kept until you close the browser. When you close the browser, all the data is deleted, with no way of getting it back (other than saving the data in databases). sessionStorage also cannot be edited with chrome extensions, so it's a great alternative to cookies.
More info: https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage, https://www.w3schools.com/jsref/prop_win_sessionstorage.asp
From archived Apple Developer docs. See the link below for more context.
Key-value storage allows you to store data locally, in either a
session store or a local store. The localStorage and sessionStorage
JavaScript objects are functionally identical except in their
persistence and scope rules:
The localStorage object is used for long-term storage. Data persists
after the window is closed and is shared across all browser windows.
The sessionStorage object is used for ephemeral data related to a
single browser window. Data stored in the sessionStorage object does
not persist after the window is closed and is not shared with other
windows.
Source:
https://developer.apple.com/library/archive/documentation/iPhone/Conceptual/SafariJSDatabaseGuide/Name-ValueStorage/Name-ValueStorage.html
'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. Closing a tab/window ends the session and clears objects in sessionStorage:'
// Save data to sessionStorage
sessionStorage.setItem("key", "value");
// Get saved data from sessionStorage
let data = sessionStorage.getItem("key");
// Remove saved data from sessionStorage
sessionStorage.removeItem("key");
// Remove all saved data from sessionStorage
sessionStorage.clear();
'There is nothing to commit in this chapter since all we had done was learning the basics of localStorage and sessionStorage.
'
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. Closing a tab/window ends the session and clears objects in sessionStorage
#KyleMit In iOS, their policies is to focus on iCloud which includes backup and so to save space. To do that from iOS 5, they clean some folder that they didn't clean before.
You can find in archive documentation that :
In iOS 5.0 and later, the system may delete the Caches directory on rare occasions when the system is very low on disk space. This will never occur while an app is running. However, be aware that restoring from backup is not necessarily the only condition under which the Caches directory can be erased.
They precise it again in other places in the actual doc like here :
In iOS, the on-disk cache may be purged when the system runs low on disk space, but only when your app is not running.
sessionStorage will last until the browser is closed. One way to save sessionStorage data is to send it to a database.
The sessionStorage and localStorage properties allow saving key/value pairs in a web browser.
The sessionStorage object stores data for only one session (the data is deleted when the browser tab is closed).
Opening multiple tabs/windows with the same URL creates sessionStorage for each tab/window.
Session storage is the same as local storage but the only difference is that data stored in session storage will clear automatically once the page session will expire.
For more Information to check this link
w3schools sessionstorage

Can user disable html5 sessionStorage?

can user disable the HTML5 sessionStorage just how he can disable cookies?
Also is sessionStorage will valid till page refresh? I mean what session actually mean, is it page refresh?
Yes. HTML5 sessionStorage (and localStorage) can be disabled, and the data can also be cleared.
It is easy to prevent browsers from accepting localStorage and sessionStorage.
In FireFox: Type “about:config” in your address bar and hit enter to
view your internal browser settings. Scroll down to
„dom.storage.enabled“, right click on it and hit „Toggle“ to disable
the DOM Storage.
In Internet Explorer: Select “Extras” -> “Internet Options” ->
“Advanced” Tab -> Go to “Security” -> uncheck “Enable DOM-Storage”
In Chrome: Open “Options” and select “Under the Hood” Tab. Click on
“Content settings…”, select “Cookies” and set “Block sites from
setting any data”.
Also note: There are some browser security plugins/extras/add-ons that will prevent localStorage. If localStorage / sessionStorage is vital to your page operation you should attempt a test read-write.
Regarding your other question: sessionStorage will survive a page refresh. localStorage will persist between browsing sessions and survive a browser restart.
can user disable the HTML5 sessionStorage just how he can disable cookies?
A User can either clear the cookies or Disallow any website from setting the cookie for themselves.Every browser has that option.
For Example-:Block Cookies
I mean what session actually mean, is it page refresh?
First of all,its not a page refresh
Most simple analogy:Session is a token which allows the user to visit any area of a web app.This token is valid untill the browser close.The moment you close the browser all the session data will get cleared.
So what if i want my data to persist a little longer,Say i want permanently(considering that user have not cleared cookies) store some value on my users browser.
LOCAL STORAGE:Local storage allows the data to persist beyond the browser close.So when the user comes back,we can use that data in our application.We can set the expiry for it.We can clear it when we want.
NOTE:IE7 + support for SessionStorage and LocalStorage
Conventional cookie storage:This is our good old way of storing some data on client.All browsers support it.But the problem is they provide too less space.
A cookie provides 4kb space and for every domain there is a limit of
around 15-20 cookies.
LocalStorage and SessionStorage comes to our rescue.They provide quite good space.
Different browsers have different capacity.
IE(10 mb)...Surprise surprise
Mozzilla(5 mb)
Chrome(2.5 mb)
So,basically i can use localStorage if i want the data to persist beyond browser close and SessionStorage if i want the data to persist with in the browser close.
There are some js availabe also..
jStorage DOCUMENTATION
persist.js DOCUMENTATION
sessionStorage is used for session-based data. It is erased when the tab is closed according to the standard. You should use localStorage to persist across tab/window closings. Of course browsers can always not support these features or disable them, so you should handle that edge case to ensure your site remains functional. The best way to do this is to revert back to using cookies or use a compatibility library like this one.

Chrome Extension Saving Data

I am working on a Chrome extension that needs to save some information (tabs info mainly) that will exist throughout the lifetime of the extension (e.g , since the user starts using it until he closes the browser).
One option is to use localstorage, however localstorage can only save Strings and that makes it very uncomfortable for me (since I have a bunch of data to save - dates , URLs , integers etc). What I'm looking for is using my own javascript objects that will live throughout the time of the extension.
Now the problem is that defining these objects in a script in some javascript files will erase them each time the user clicks on the browser action . In other words I have a browser action called popup.html that includes a javascript file (in which I want to save my objects) and every time the user clicks on the browser action all the objects I defined in the JS file are lost, yet I want everything to be persisted .
What option do I have to keep data that persists through many clicks on the browser action and that is NOT localstorage?
You really should use localStorage (you may use JSON.stringify and JSON.parse).
If you really don't want to use localStorage nor a server side storage, use IndexedDb : https://developer.mozilla.org/en/IndexedDB/Using_IndexedDB
Try using the Filesystem API's persistent storage. That is more reliable than localStorage. localStorage will be cleared once the user clears the cache, cookies etc. Filesystem is more reliable.
This answer about using chrome.storage worked for me far better than the others.
https://stackoverflow.com/a/14009240/766115
It's like localStorage, but works between the popup / background and content scripts.

Prevent loss of variables when browser reload button is pressed [duplicate]

This question already has answers here:
Persist variables between page loads
(4 answers)
Closed 7 years ago.
Is it possible to keep my (global) variables when the page is reloaded? If yes, how?
Thanks for any help.
Best regards.
Try this cookie-less javascript function.
It basically store your data in the window.name property which does not clear the value when you reload the page or goes to another site.
You can persist data across page reloads via something like window.localStorage, window.sessionStorage (proprietary Mozilla extension) or database abstraction (window.openDatabase) provided by some of the WebKit -based browsers. See this article on MDC for a nice overview of Storage interfaces and this WebKit article on their database introduction.
In the same style you can store string values in the hash key.
Using the property:
window.location.hash = 'flight/105';
Then when refreshing the page you initialize back your variables.
The JavaScript environment will be reset when the browser leaves your page. However, you could register an onUnload handler to serialise your array to a cookie, then check for this every time the page is loaded and unserialise it if present.
Does your browser have a reset button, or do you mean the reload button?
When the page loads, everything is loaded fresh. There is nothing left from any previous page. The only place to store anything that survives loading a page is in a cookie.
Note that the amount of data that you can put in cookies is limited to a few kilobytes per site. The exact limit varies from browser to browser, but you can't expect to be able to put more than perhaps a kilobyte or two worth of data in cookies.
Are you talking about Cookies? If so you might want to review this open-source module
This will easily allow you to store cookies, that is data, even after a browser reload click. This makes doing it really easy and it is what I use.
var cookie = new HTTP.Cookies();
cookie.write('mydata', 'myvalue', '+1y');
//later on you can get that data EVEN AFTER a reload
var x = cookie.read('mydata');
You probably shouldn't try to make a cookies implementation from scratch though because it is very painful and you have to do a lot of testing across web browsers, such as to make sure Internet Explorer works.

Categories

Resources