How to bind to localStorage change event using jQuery for all browsers?

JqueryHtmlGoogle Chrome

Jquery Problem Overview


How do I bind a function to the HTML5 localStorage change event using jQuery?

$(function () {

  $(window).bind('storage', function (e) {
    alert('storage changed');
  });

  localStorage.setItem('a', 'test');

});

I've tried the above but the alert is not showing.

Update: It works in Firefox 3.6 but it doesn't work in Chrome 8 or IE 8 so the question should be more 'How to bind to localStorage change event using jQuery for all browsers?'

Jquery Solutions


Solution 1 - Jquery

It turns out that this is actually working correctly and I have misinterpreted the specification

> When the setItem(), removeItem(), and clear() methods are called on a Storage object x that is associated with a local storage area, if the methods did something, then in every Document object whose Window object's localStorage attribute's Storage object is associated with the same storage area, other than x, a storage event must be fired

In other words, a storage event is fired on every window/tab except for the one that updated the localStorage object and caused the event.

So the event was not fired because I only had one window/tab open. If I place the above code in a page and open the page in two tabs I would see the event fired in the second tab.

This answer on the problem contains more details.

Solution 2 - Jquery

Here's how to do it in JQuery:

 $(window).bind('storage', function (e) {
     console.log(e.originalEvent.key, e.originalEvent.newValue);
 });

Accessing e.key directly does not work. You need to use e.originalEvent.key.

Some browsers will only send storage notifications to other tabs, and some won't. (Firefox will send storage events to its own tab, but with key set to null, it seems like).

Solution 3 - Jquery

One thing to mention is that the event handler is only called on .setItem if the item actually changes. I was ripping my hair out trying to get this to work until I realized you can't keep running setItem with the same value.

I am on Chrome Version 54.0.2840.71 m

Here is a test (open this in two browser tabs).

if (window.addEventListener)
			addEventListener('storage', storage_event, false);
		else if (window.attachEvent)
			attachEvent('onstorage', storage_event, false);
		function storage_event(e) {
			console.log("Time is now "+ e.newValue);
		}

		setInterval(function () {
			var time=new Date().getTime();
			localStorage.setItem("time", time);
			console.log("Setting time to "+time);
		}, 1000)

Solution 4 - Jquery

You could always use a utility like localDataStorage to fire the events for you, in the same window/tab, whenever a key value changes, such as those made by the set or remove methods. You can also use it to transparently set/get any of the following "types": Array, Boolean, Date, Float, Integer, Null, Object or String.

[DISCLAIMER] I am the author of the utility [/DISCLAIMER]

Once you instantiate the utility, the following snippet will allow you to monitor the events (in vanilla JS, since jQuery examples have already been given):

function localStorageChangeEvents( e ) {
    console.log(
        "timestamp: "     + e.detail.timestamp + " (" + new Date( e.detail.timestamp ) + ")" + "\n" +
        "key: "           + e.detail.key     + "\n" +
        "old value: "     + e.detail.oldval  + "\n" +
        "new value: "     + e.detail.newval  + "\n"
    );
};
document.addEventListener(
    "localDataStorage"
    , localStorageChangeEvents
    , false
);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDavid GlennView Question on Stackoverflow
Solution 1 - JqueryDavid GlennView Answer on Stackoverflow
Solution 2 - JqueryFlimmView Answer on Stackoverflow
Solution 3 - Jquerykmoney12View Answer on Stackoverflow
Solution 4 - JqueryMacView Answer on Stackoverflow