How do I bind event to sessionStorage?

Tesco picture Tesco · Apr 21, 2012 · Viewed 26.4k times · Source

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?

Answer

Nicu Surdu picture Nicu Surdu · Jan 22, 2014

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:

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