TKoL
TKoL

Reputation: 13932

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.

Upvotes: 10

Views: 7711

Answers (1)

kemotoe
kemotoe

Reputation: 1777

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.

Upvotes: 8

Related Questions