javascript 在同一窗口上使用 localStorage 监听更改

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26974084/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 06:46:01  来源:igfitidea点击:

Listen for changes with localStorage on the same window

javascripteventslocal-storage

提问by f.lorenzo

I want to listen for changes that are happening in the localStorage API on the same page (Not in multiple tabs like the spec says).

我想侦听同一页面上 localStorage API 中发生的更改(而不是像规范所说的那样在多个选项卡中)。

I am currently using this code:

我目前正在使用此代码:

var storageHandler = function () {
    alert('storage event 1');
  };

  window.addEventListener("storage", storageHandler, false);

localStorage.setItem('foo', 'bar');

Does anyone know a vanilla JavaScript way to listen to events on localStorage on one page (no jQuery)

有没有人知道在一个页面上侦听 localStorage 上的事件的普通 JavaScript 方式(没有 jQuery)

回答by Roman Bekkiev

Since JS is dynamical language just rewrite original functions.

由于 JS 是动态语言,因此只需重写原始函数即可。

var originalSetItem = localStorage.setItem; 
localStorage.setItem = function(){
    document.createEvent('Event').initEvent('itemInserted', true, true);
    originalSetItem.apply(this, arguments);
}

回答by Amsvartner

Updated above answer, as document.createEvent now is part of an old, deprecated API.

更新了上面的答案,因为 document.createEvent 现在是旧的、已弃用的 API 的一部分。

var originalSetItem = localStorage.setItem;

localStorage.setItem = function(key, value) {
  var event = new Event('itemInserted');

  event.value = value; // Optional..
  event.key = key; // Optional..

  document.dispatchEvent(event);

  originalSetItem.apply(this, arguments);
};

var localStorageSetHandler = function(e) {
  alert('localStorage.set("' + e.key + '", "' + e.value + '") was called');
};

document.addEventListener("itemInserted", localStorageSetHandler, false);

localStorage.setItem('foo', 'bar'); // Pops an alert

https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events

https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events