How to detect if sessionStorage is going to die? - javascript

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 },
...
]

Related

Reset variable on every new session using localstorage

I am trying to run something only once at the beginning of the user session spanning multiple pages.
I was trying to use sessionStorage to test if a variable exists which defaults to false initially, but it is not persisting in some browsers due to a JavaScript redirect in the script:
window.location.href
Is there a way to mimic this with localstorage which persists more reliably?
i.e. to do something only once at the beginning of each new user session. The session may have multiple pages so a single javascript variable won't work.
update: as requested in the comments, the basic logic is:
new session opened.
redirect once to last page viewed.
set redirected to true. to prevent this from happening again.
I realize there are other ways to do this besides localstorage. would be nice to use that though if possible.
you could check if the item already exists or if it is null with:
localStorage.getItem("itemname");
If it doesnt exists (== null) it is the first "run" so you could set it to prevent further loop execution. use:
localStorage.setItem("itemname", "notNull");

Local storage - saving data from multiple tabs

I'm using a localStorage to store some stuff ( profile visits history ).
Every time profile is open, i get object, add more entries and update object.
This can lead to data loss (example: tab1:open, tab2:open, tab1:save, tab2:save).
Now, if I hold cntrl and open many new tabs at once, how to pervent data loss?
Didn't find anyhing about localStorage locking.
You can increment a variable instead of getting a whole new object, or push that new object into an array and calculate the total views getting the length of that array. The localStorage is shared across the different tabs as long as they are in the same domain.
Option 1.
Check and put a variable (e.g. editing) to localStorage when a tab is opened. So if another tab is open, you can create a warning on new tab. Clear that variable onPageUnload event. (Pessimistic Lock)
Option 2.
Update/put a variable (e.g. saveTime or saveCount) on save action. When a tab is opening, retrieve this variable and on save action check if the variable is remaning the same. If value is not the same, warn the user that he/she is editing an oldest version of the data. (Optimistic Lock)
Optimistic Lock vs Pessimistic Lock

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

How to maintain the page state when browser back button is clicked?

I have a page with Client side paggination and Filtration. The page lists around 200-300 prouducts.
The page contains some filters like Category,Manufacturer and Weight.
Clicking upon any of the page number or filter, I am manupulating the page content on client side using Jquery.
Everything is working fine till this step. Now there is a usecase where I am facing problem.
Lets say a user comes to our product listing page and click on some of the filters and gets a list of products.
Now he clicks on a particular product , which redirects him to the product page to view the details of the product.
But now when the user clicks on the back button , the user gets the page with the intial state without any filter selected.
Is there any way user will get the page with the filters previously selected on clicking the back button?
You can use some of the following to store data across multiple pages.
Store data in cookies.
Store data in local storage.
Store data in the session on the server.
Make the data part of your URL (use hash or query string for the filter parameters). Note that changing query string causes page reload.
If using cookies, local storage, or hash, you'll need to add JavaScript code to your page that loads and applies the stored data on page load.
There is a number of ways to do this:
If you are dealing with html5 history and a single-page application, then you are not reloading the page. But based on your question, I assume this is not what you are dealing with.
Store something in the URL. For an example of this, look at the filters on TotalHockey, e.g. http://www.totalhockey.com/Search.aspx?category_2=Sticks%2fComposite%20Sticks&chan_id=1&div_main_desc=Intermediate&category_1=Sticks so when you go backwards, the URL contains the entire state.
Use localstorage, if you have a browser that supports it.
use cookies with the $.cookie API
Store it on the session in the server.
You can store the Search Filter Data in session just after submitting on the filter input and on each ajax request (Loading your product listing), you can check the search filter inputs stored in the session and show the data according to them. If search session is empty then show whole listing.
You can also store the full ajax request URL (if GET method is used) in the session after searching the record and hit that particular URL again after coming back from product detail page.

store temporary data on indexedDB for current session

Is there a way to store temporary data on indexedDB the same way as sessionStorage:no available to other sessions (tabs) of the same domain and expire when the session is closed (affect some items on an storeObject or the whole storeObject)?
I can create a storeObject with a random name and add unload event listener to delete this storeObject when the user is exiting the page. but the problem here is that the storeObject will be deleted even if the user is just changing from a page to an other on the same domain or refreshing the page,... (same session).
I know there is some implementations of sessionStorage-like storages based on document.cookie API which is not a perfect solution for my case.
I'm not sure if there is a way to do what you want to do. I believe that indexDB is persistent until deleted. You could delete based on a timestamp, this can only happen after the user returns, or logoff button.
This may help you may be able to user localStorage if your not storing to much data:
http://www.sitepoint.com/an-overview-of-the-web-storage-api/
If you are worried about concurrent data overrides you can implement locks:
http://balpha.de/2012/03/javascript-concurrency-and-locking-the-html5-localstorage/#comments

Categories