yenssen
yenssen

Reputation: 1191

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

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!

Upvotes: 1

Views: 5364

Answers (2)

HBP
HBP

Reputation: 16043

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.

Upvotes: 2

Ivan Zuzak
Ivan Zuzak

Reputation: 18782

There is definitely a better way -- using events built into the localstorage mechanism. When you update localstorage in tab2, tab1 will get an update event which you can then use as a signal to read the new value from localstorage.

For more info, see:

Bug with Chrome's localStorage implementation?

http://diveintohtml5.info/storage.html

Upvotes: 2

Related Questions