实现说明
除了函数 handler、listenForRemotePrefs,文件里再无其他定义。
使用要点
- 浏览器才是这里的运行环境:
window、localStorage在 Node 里拿不到。 - 直接运行文件,输出会带上标签,比如
storage events need a browser with a second tab——输出的每一行都能指回产生它的那次调用。
常见问题
「storage 事件只在别的标签页触发」能在裸 Node.js 里跑吗?
不能——它用到 window、localStorage。这些 API 只在浏览器里有效,裸 Node 进程没有这些能力,请放到页面(或 DevTools 控制台)里执行。
签名一览:const handler = (event: StorageEvent)
核心语句
return () => window.removeEventListener("storage", handler);
const unsubscribe = listenForRemotePrefs((key, value) => {
console.log("remote change:", key, "->", value);
});
onRemote(event.key ?? "<cleared>", event.newValue);
代码示例
// The storage event fires in EVERY other tab/window sharing the origin -
// the tab that wrote the value does NOT receive its own event
function listenForRemotePrefs(onRemote: (key: string, value: string | null) => void): () => void {
const handler = (event: StorageEvent): void => {
if (event.key === "reader-theme" || event.key === null) {
onRemote(event.key ?? "<cleared>", event.newValue);
}
};
window.addEventListener("storage", handler);
return () => window.removeEventListener("storage", handler);
}
if (typeof window === "undefined") {
console.log("storage events need a browser with a second tab");
} else {
const unsubscribe = listenForRemotePrefs((key, value) => {
console.log("remote change:", key, "->", value);
});
// Writes in THIS tab fire no storage event here; another tab would see one
localStorage.setItem("reader-theme", "dark");
console.log("wrote locally; own tab sees no storage event");
unsubscribe();
}