How to detect when the contents of a specific localStorage variable changes between the browser tabs?

advertisements

I want to communicate between two different tabs in the same browser (on the same domain).

When a specific event fires in the second tab, I change a localstorage variable value (using Javascript). I want to detect this change on the first tab. The variable is named "status" and the value changes from 0 to 1

I was thinking for a possible solution and I think that using a timer on the first tab will work, but I think also that there must be a better way.

Do you know if there is any way to detect when the "status" variable value changes without using a timer?

Thanks a lot!


It seems that Storage events should provide what you need.

The HTML spec on storage events ( http://dev.w3.org/html5/webstorage/#the-storage-event ) says :

The storage event is fired when a storage area changes, as described in the previous two sections (for session storage, for local storage).

When this happens, the user agent must queue a task to fire an event with the name storage, which does not bubble and is not cancelable, and which uses the StorageEvent interface, at each Window object whose Document object has a Storage object that is affected.

Note the final clause, all windows which have access to the storage should be notified of any change.

However note the following clause in previous section of the spec :

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, as described below.

So the document which provoked the change is not alerted.