开发者

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

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?'


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.


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).


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)


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
);


An update to @Flimm's answer; .bind() method is deprecated after jQuery 3.0 so using .on() method is recommended.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜