简体   繁体   English

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

[英]Listen for changes with localStorage on the same window

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)

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

Updated above answer, as document.createEvent now is part of an old, deprecated API.更新了上面的答案,因为 document.createEvent 现在是旧的、已弃用的 API 的一部分。

const originalSetItem = localStorage.setItem;

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

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

  document.dispatchEvent(event);

  originalSetItem.apply(this, arguments);
};

const 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

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

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