Tesco
Tesco

Reputation: 445

How do I bind event to sessionStorage?

I can successfully bind an event for a change to localStorage (using jquery):

$(window).bind('storage', function(e)
{
    alert('change');
});

localStorage.setItem('someItem', 'someValue');

If I use sessionStorage, the event will NOT fire:

 $(window).bind('storage', function(e)
{
    alert('change');
});

sessionStorage.setItem('someItem', 'someValue');

Why is this?

Upvotes: 32

Views: 48908

Answers (3)

Nicu Surdu
Nicu Surdu

Reputation: 8341

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.

EDIT:

I've made the following example to illustrate the above statement:

http://codepen.io/surdu/pen/QGZGLO?editors=1010

The example page has two buttons that trigger a local and a session storage change.

It also embeds an iframe to another codepen that listens for storage events changes:

http://codepen.io/surdu/pen/GNYNrW?editors=1010 (you should keep this opened in a different tab.)

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 "Write session" only the embedded iframe captures the event.

Upvotes: 32

Ruben Serrate
Ruben Serrate

Reputation: 2783

This question seems to be getting quite a few views, so I will just post this as extra info.

In case you want to respond exclusively to updates on the sessionStorage object, you can just ignore the events caused by localStorage:

$(window).on('storage',function(e){
   if(e.originalEvent.storageArea===sessionStorage){
     alert('change');
   } 
   // else, event is caused by an update to localStorage, ignore it
});

I hate jQuery, so will post a the native version as well:

window.addEventListener('storage',function(e){
   if(e.storageArea===sessionStorage){
     alert('change');
   } 
   // else, event is caused by an update to localStorage, ignore it
});

Upvotes: 14

James Allardice
James Allardice

Reputation: 166061

That is the way it's meant to be I think. From the spec (emphasis added):

When the setItem(), removeItem(), and clear() methods are called on a Storage object x that is associated with a session storage area, if the methods did something, then in every Document object whose Window object's sessionStorage attribute's Storage object is associated with the same storage area, other than x, a storage event must be fired

I think what that means is that the event will be fired in any other document sharing the session storage object, but not the document that caused the event to fire.

Update

Here's another very similar question which seems to agree with what I've mentioned above (the answer quotes the same paragraph from the spec).

Upvotes: 19

Related Questions