Storage Event Fires In Other Tabs

Listen for the storage event to react to localStorage changes made in other tabs - the writing tab itself never receives the event.

TypescriptConfig Management

Code

typescriptsnippet
23 lines
// 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();
}

Output

Captured from a sandboxed run of this snippet in the build pipeline.

storage events need a browser with a second tab

Walking through the code

Under the hood: the functions handler and listenForRemotePrefs.

Points of care

  • Dependency-free as built — no registry, no lockfile entry.
  • A browser is the runtime here: window, localStorage are not available in Node.

Using it

Signature: const handler = (event: StorageEvent)

Every stage prints a tag of its own: storage events need a browser with a second tab, remote change:, wrote locally; own tab sees no storage event.

Key statements

return () => window.removeEventListener("storage", handler);
const unsubscribe = listenForRemotePrefs((key, value) => {
  console.log("remote change:", key, "->", value);
});
onRemote(event.key ?? "<cleared>", event.newValue);

Interactive Tools for This Topic

FAQ

Does Storage Event Fires In Other Tabs run in plain Node.js?
No — it touches `window` and `localStorage`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.