Sharing data across windows using localStorage

One of a common requirement in some web applications is that of sending messages and data across windows (of the same origin). Doing this is not easy and requires the help of cookies and a bit of JavaScript. Now with HTML5 and its localStorage feature we can accomplish this quite easily.

Storage Events

Whenever a localStorage object is changed using the setItem(), removeItem(), or clear() functions, the storage event is fired (across multiple windows of the same origin) by the browser, we can trap this event and use it to share messages or data across windows. Check the following demo to see how this works in a simple case.

The above example works by using the storage event of the Window object. So whenever the localStorage object is modified, the storage event is fired and we use it to update the window content.

window.addEventListener("storage", displayStorageEvent, true);

Below is the skeleton code for the demo example.

// Input element
var data = document.getElementById('data');
// Element to display the updated data
var output = document.getElementById('event-data');
 
function displayStorageEvent(e) {
    if (e.key == 'storage-event') {
        output.innerHTML = e.newValue;
    }
}
 
function updateStorageEvent() {
    localStorage.setItem('storage-event', this.value);
}
 
window.addEventListener("storage", displayStorageEvent, true);
data.addEventListener("keyup", updateStorageEvent, true);

Sharing messages

Although in the above example we are sharing data across windows, we can use the same mechanism to share messages. In the above example we are using the ‘storage-event’ key to store the data we type in the input box. Instead we can pass a simple message. The syntax remains the same, only the semantics changes.

/* Store the 'checkPassword' message in the 'app.message.auth' key */
localStorage.setItem('app.message.auth', "checkPassword");
 
/* Store the 'dataSave' message in the 'app.message.status' key */
localStorage.setItem('app.message.status', "dataSave");

Security concerns

As the communication can only happen between windows with the same origin, there is little risk of data leak between sites. Still you should refrain from storing sensitive information in the storage.

Possible applications

Now that we have seen a simple proof of concept of ‘cross window messaging and data sharing’, what are the potential use cases of the same. An idea without a concrete and useful application is useless. Although many people will have good ideas for the above concept, I presently lack one. So if you can think of some nice use cases for this, please voice your ideas in the comments section.



One thought on “Sharing data across windows using localStorage

Comments are closed.