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?
Because the sessionStorage is an instance of the Storage type, you can manage data using the Storage's methods: setItem(name, value) – set the value for a name. removeItem(name) – remove the name-value pair identified by name.
The storage event of the Window interface fires when a storage area ( localStorage ) has been modified in the context of another document. Note: This won't work on the same page that is making the changes — it is really a way for other pages on the domain using the storage to sync any changes that are made.
The sessionStorage exists only within the current browser tab. Another tab with the same page will have a different storage. But it is shared between iframes in the same tab (assuming they come from the same origin).
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.
That is the way it's meant to be I think. From the spec (emphasis added):
When the
setItem()
,removeItem()
, andclear()
methods are called on aStorage
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With