← 中文资源

简体中文版本

storage 事件只在其他标签页触发

storage 事件广播给同源的其他标签页,写入方自己收不到:event 带出 key、oldValue、newValue,key 为 null 表示对方调用了 clear();值一律是字符串,对象要自行 JSON.parse。

阅读英文原文

使用要点

  • 用到了 window、localStorage,需要在浏览器环境运行,Node 里直接跑会缺 API。
  • 直接运行文件,输出会带上标签,比如 storage cleared elsewhere、key:——输出的每一行都能指回产生它的那次调用。

常见问题

「storage 事件只在其他标签页触发」能在裸 Node.js 里跑吗?

不能——这类 API 归浏览器环境所有(window、localStorage),Node 里不存在。请在页面或 DevTools 控制台中运行。

核心语句

window.addEventListener('storage', (event) => {
  // key is null: another tab called clear()
  if (event.key === null) {
    console.log('storage cleared elsewhere');
    return;
  }
  console.log('key:', event.key, event.oldValue, '->', event.newValue);
});

代码示例

// the storage event fires only in the "other" same-origin tabs; the writing tab itself never receives it
window.addEventListener('storage', (event) => {
  // key is null: another tab called clear()
  if (event.key === null) {
    console.log('storage cleared elsewhere');
    return;
  }
  console.log('key:', event.key, event.oldValue, '->', event.newValue);
});

// a write from this tab never triggers its own listener
localStorage.setItem('theme', 'dark');

// when another tab writes the same key, this page receives:
// key: theme null -> dark
// oldValue/newValue are strings; objects must be JSON.parse-ed by hand