Listening for Storage Events
React to cross-tab storage changes with the storage event.
Cross-Tab Communication
Web Storage fires a storage event on every other same-origin tab whenever localStorage changes. This is the simplest way to keep multiple open tabs of the same app in sync — for example, propagating a logout or a theme switch.
Registering a Listener
Attach the handler on window: window.addEventListener("storage", handleStorage). The listener fires only in other tabs/windows of the same origin — never in the tab that performed the change itself, which already knows about the update.
window.addEventListener("storage", (e) => {
console.log("key:", e.key, "new:", e.newValue);
});All lessons in this course
- localStorage vs sessionStorage
- Getting Setting and Removing Items
- Listening for Storage Events
- Security What Never to Store in Storage