Storage event not firing

2019-06-22 18:34发布

问题:

Attaching the event:

$(window).on("storage", function (e) {
   //callback not getting hit
});

Trying to fire the event:

localStorage.setItem("test", "123");

I have two tabs open, both listening to the storage event. I can see the localStorage getting updated correctly on both tabs. However when I change localStorage on one tab, the other never fires the event. Any ideas?

Tried on Chrome/Firefox. Domain format is https://www.xxx.yyy.zzz.

回答1:

Problem was caused by document.domain overriding in code. After I removed the document.domain setter, events worked correctly.

Seems this is caused by a bug in Chrome.

https://bugs.chromium.org/p/chromium/issues/detail?id=136356&q=label%3AOWP-Standards-Compatibility&colspec=ID%20Pri%20M%20Stars%20ReleaseBlock%20Cr%20Status%20Owner%20Summary%20OS%20Modified



回答2:

StorageEvent is fired in different page with the same domain.

From MDN

The StorageEvent is fired whenever a change is made to the Storage object.

This won't work on the same page that is making the changes — it is really a way for other pages on the domain using the storage to sync any changes that are made。



回答3:

window.addEventListener('storage', function (e) {
      console.log("storage event occured here");
},false);

Storage Listner get called in other tabs , other than source tab. Just add debugger to other tabs.



回答4:

Did you tried this simpler example

window.addEventListener('storage', function (e) {
   console.log("storage event occured");
});


回答5:

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:

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