javascriptjqueryeventssessionstorage

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?


Solution

  • 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).