Storage Events
The storage event fires in other tabs (not the current one) when localStorage changes. Use it to sync state across multiple tabs.
The storage event fires in other tabs (not the current one) when localStorage changes. Use it to sync state across multiple tabs.
// Listen for changes from other tabs
window.addEventListener("storage", (event) => {
console.log(event.key); // Changed key
console.log(event.oldValue); // Previous value
console.log(event.newValue); // New value
console.log(event.url); // URL of the tab that changed it
if (event.key === "theme") {
document.body.dataset.theme = event.newValue;
}
});
// Trigger by changing localStorage in another tab
localStorage.setItem("theme", "dark");
The storage event fires in OTHER tabs — the tab making the change does not receive the event.
More in JavaScript