The storage Event
You'll learn how to detect when localStorage or sessionStorage changes in other browser tabs or windows using the built-in storage event.
What Is the storage Event?
The storage event fires on a window object whenever localStorage or sessionStorage is modified in a different tab or window from the same origin. Think of it like a notification system between tabs—when Tab A changes storage, Tab B gets a message about it.
Important: The event does not fire in the same tab that made the change. It only notifies other tabs.
How It Works
To listen for storage changes, attach an event listener to the window object:
window.addEventListener('storage', function(event) {
console.log('Storage changed!');
console.log('Key:', event.key);
console.log('Old value:', event.oldValue);
console.log('New value:', event.newValue);
console.log('Storage area:', event.storageArea);
console.log('URL where change occurred:', event.url);
});
The event object provides useful properties:
key: The storage key that changed (ornullifclear()was called)oldValue: The previous value (as a string)newValue: The new value (as a string, ornullif removed)storageArea: Reference to the affected storage (localStorage or sessionStorage)url: The URL of the page that made the change
Real-World Use Case
This is perfect for syncing state across multiple tabs. If a user logs out in one tab, all other tabs can detect the storage change and update their UI accordingly.
Key Takeaway: The storage event lets different tabs communicate by listening for changes to localStorage or sessionStorage, enabling synchronized experiences across browser windows.