Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sessionStorage changes aren't firing 'storage' event

I was following this here to see if I could enable updates on all open webpages of my site if someone has multiple tabs open.

Basically, I set the listener and check to see if the cart key was changed

window.addEventListener('storage', function(e) {
  if (e.key === "cart") {
    console.log(`cart changed: ${e.newValue}`);
  }
});

When I change localStorage.cart from another tab on the same website, the event fires just fine in the first tab:

setInterval(function(){
    localStorage.cart = "localStorage 1";
    setTimeout(function(){
        localStorage.cart = "localStorage 2";
    },2000);
},4000);

But when I use sessionStorage instead of localStorage it doesn't:

setInterval(function(){
    sessionStorage.cart = "sessionStorage 1";
    setTimeout(function(){
        sessionStorage.cart = "sessionStorage 2";
    },2000);
},4000);

Does the storage event only fire for localStorage and not sessionStorage?

Tested on chrome only.

like image 850
TKoL Avatar asked Oct 13 '17 16:10

TKoL


People also ask

What event is fired after web storage update?

The storage event of the Window interface fires when a storage area ( localStorage ) has been modified in the context of another document.

Does sessionStorage persist on refresh?

Web storage objects localStorage and sessionStorage allow to save key/value pairs in the browser. What's interesting about them is that the data survives a page refresh (for sessionStorage ) and even a full browser restart (for localStorage ).

Is sessionStorage persistent?

The difference is that with sessionStorage , the data is persisted only until the window or tab is closed. With localStorage , the data is persisted until the user manually clears the browser cache or until your web app clears the data.

Can you modify session storage?

Yes, users can always modify the values of their own storage.


1 Answers

The sessionStorage is isolated for each tab, so they can't communicate. Events for sessionStorage are triggered only in between frames on the same tab.

These codepens provide a good example

Storage Writer writes to storage

function writeSession()

    {
      sessionStorage.setItem("test", Math.random());
    }

    function writeLocal()
    {
      localStorage.setItem("test", Math.random());
    } 

Storage Reader listens for storage event (keep this open in a different tab.)

window.addEventListener('storage', function(e) {  

  if(e.storageArea===sessionStorage) {
    $("#output").append('Session storage change <br>');   
  }

  if(e.storageArea===localStorage) {
    $("#output").append('Local storage change <br>');   
  }

});

You will notice that when you press the "Write local" button, in both the iframe and the opened tab the event is captured, but when you press the "Session write" only the embedded iframe captures the event.

like image 151
kemotoe Avatar answered Oct 17 '22 14:10

kemotoe