存储事件未触发

Storage event not firing

附加事件:

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

正在尝试触发事件:

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

我打开了两个选项卡,都在监听存储事件。我可以在两个选项卡上看到 localStorage 得到正确更新。但是,当我在一个选项卡上更改 localStorage 时,另一个选项卡永远不会触发该事件。有什么想法吗?

试穿 Chrome/Firefox。域格式为 https://www.xxx.yyy.zzz.

问题是由代码中的 document.domain 覆盖引起的。在我删除 document.domain setter 后,事件正常运行。

这似乎是由 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

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

Storage Listner 在除源选项卡之外的其他选项卡中被调用。只需将调试器添加到其他选项卡即可。

您始终可以使用 localDataStorage 之类的实用程序在相同的 window/tab 中为您触发事件,只要键值发生变化,例如 set 或 remove 方法所做的更改。您还可以使用它透明地 set/get 以下任何一项 "types":Array、Boolean、Date、Float、Integer、Null、Object 或 String。

[免责声明]我是该实用程序的作者[/免责声明]

实例化该实用程序后,您可以使用以下代码片段监视事件:

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

StorageEvent 在具有相同域的不同页面中触发。

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。

即使在不同的 tabs/pages 之间进行测试,但仍未看到事件...我发现事件只会在密钥已经存在的情况下触发。

看起来更像是一个onchange事件。

localStorage键设置一个默认值,如果偶数undefined然后测试。

我将其称为 Chrome 错误,因为 Firefox 和 Safari 可以正常启动,但事实就是如此。

正如其他人在回答中指出的那样,只有在 localStorage 在另一个浏览器的 tab/window(属于同一应用程序),但 不在 当前选项卡的上下文中。

检测当前选项卡中的存储更改:

window.addEventListener('storage', console.log)

window.localStorage.setItem('test', '123')
window.dispatchEvent( new Event('storage') ) // <----- 

已调度手动 storage 事件。

这将有效地触发 storage 事件侦听器 两次 在其他 tabs/windows (同一应用程序)上,但在某些情况下这不应该是个问题。

额外指向 is you can fire StorageEvent 而不是 Event 并传入一个对象,以便触发的事件与浏览器默认值匹配。

const oldValue = window.localStorage.getItem('test');
window.localStorage.setItem('test', newValue);
const event = new StorageEvent('storage', {
  key: 'test',
  oldValue,
  newValue,
  ...
});

window.dispatchEvent(event);