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.
Code
// 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 tabWalking 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,localStorageare 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
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.Indentation ConverterConvert leading indentation between tabs and spaces at a chosen width, leaving inner content untouched.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.