简体   繁体   English

添加存储事件监听器不起作用

[英]Add Storage Event Listener didn't work

I use method addEventListener with storage parameter to detect changing of storage. 我使用带有存储参数的方法addEventListener来检测存储的更改。 However, it didn't work. 但是,它没有用。 I do it on Chrome. 我在Chrome上执行。 What is wrong? 怎么了?

 window.addEventListener('storage', function(storageEvent){ console.log(storageEvent); }); function setData(){ localStorage.setItem('superpower', 'heatvision'); } function clearData(){ localStorage.clear() } 
 <button onClick="setData()">Set</button> <button onClick="clearData()">Clear</button> 

It's impossible to detect storage changes in the same window like that. 不可能在同一窗口中检测到存储更改。 Since you're using getItem and setItem , just try using a wrapper method, and calling that wrapper method instead: 由于您使用的是getItemsetItem ,因此只需尝试使用包装器方法,然后调用该包装器方法即可:

const myLSInterface = {
  listeners: [],
  set: function(key, value) {
    localStorage.key = value;
    const thisEventObj = { key, value };
    this.listeners.forEach(listener => listener(thisEventObj));
  },
  addListener: function(listener) {
    this.listeners.push(listener);
  },
};
myLSInterface.addListener((eventObj) => {
  console.log(JSON.stringify(eventObj));
});
myLSInterface.set('foo', 'bar');

See live (can't be done on SO due to security issues): 即时观看(由于安全问题,无法在SO上完成):

https://jsfiddle.net/0pgyxotn/ https://jsfiddle.net/0pgyxotn/

From Web_Storage_API Web_Storage_API

if you load this page in another tab, then make changes to your choices in the landing page, you'll see the updated storage information outputted as the StorageEvent is fired 如果您在另一个标签页中加载此页面,然后在登录页面中更改选择,则会看到在触发StorageEvent时输出的更新的存储信息

So basically it means that if the storage is changed from another tab then it will reflect in the landing page. 因此,从根本上讲,这意味着如果从另一个选项卡更改了存储,则它将反映在登录页面中。

Take an example of this demo . 以这个演示为例。 If you open this link in two different tab , you will see the changes in the second tab is reflecting in the first tab, while he change in the first tab is not reflecting in the same page. 如果您在两个不同的选项卡中打开此链接,您将看到第二个选项卡中的更改反映在第一个选项卡中,而他在第一个选项卡中的更改未反映在同一页面中。

There is one addon on mdn. mdn上有一个插件。 You can also explore this 您也可以探索这个

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM