Quantcast
Viewing latest article 15
Browse Latest Browse All 40

localStorage and sessionStorage events to send messages acrosss browser instances

This is a somewhat underused and lesser known feature of HTML5 localStorage API. The spec 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.

This allows for a neat inter-browser window communication trick that can let multiple window instances of the same domain (same origin applies) to talk to each other.

Imagine you have the following situation: same site is open twice, the user then logs off in one of the two instances. Ideally, instance #2 should also find out about the fact they logged off and adjust accordingly.

// some imaginary event handler on an element
$('.log-off').on('click', function(){
    // pretend to do something on an app controller
    App.controller.logOff();

    // store something in localStorage
    localStorage.setItem('state', 'logged out');
});

// listen for this event
window.addEventListener('storage', function(storageEvent){
    // the event seems not to fire on own state changes, only other windows
    console.log(storageEvent);
    App.controller.setLoginState(storageEvent.newValue);
}, false);

The event object itself looks like this:

type storage
target Window /_display/
currentTarget Window /_display/
eventPhase 2
bubbles false
cancelable false
timeStamp 1371809245502028
defaultPrevented false
stopPropagation stopPropagation()
preventDefault preventDefault()
initEvent initEvent()
stopImmediatePropagation stopImmediatePropagation()
originalTarget Window /_display/
explicitOriginalTarget Window /_display/
preventBubble preventBubble()
preventCapture preventCapture()
getPreventDefault getPreventDefault()
isTrusted true
key state
oldValue logged in
newValue logged out
url http://localhost/_display/
storageArea 1 item in Storage state="logged out"

Type can be session or local. You can reconcile paths and more.

To play with it, open this http://jsfiddle.net/dimitar/jTfdq/ twice and open your console, then keep on running the fiddles in alternative windows.


Viewing latest article 15
Browse Latest Browse All 40

Trending Articles