When someone interacts with a webpage, the browser sends events to the relevant JavaScript code. The storage event happens when another same-origin browsing context changes localStorage.
When storage happens
Another same-origin browsing context changes localStorage.
You can listen for it using addEventListener(). That keeps event handling separate from HTML attributes such as onclick and works well with modern code organization.
A small working example
<p>Try the relevant browser action described below.</p>
<p id="event-status" role="status">Waiting for storage...</p>
<script>
const eventTarget = window;
const eventStatus = document.getElementById("event-status");
if (eventTarget) {
eventTarget.addEventListener("storage", (eventDetails) => {
eventStatus.textContent = "storage event received";
console.log(eventDetails.type, eventDetails.target);
});
}
</script>
Reading the code
The browser listens for storage on the relevant target. When the event occurs, the callback receives eventDetails, updates the status message and logs the event name and target in Developer Tools.
Open two tabs and update localStorage from the other tab; the tab making the change does not receive its own event.
The event exposes key, oldValue and newValue for changes from another same-origin context.
Some events need a specific browser condition, another tab or window, or a Web Component to reproduce. Read the trigger steps carefully before deciding that an event handler is not working.
Try it in your browser
Open the page, show the Console panel, and follow this test: Open two tabs and update localStorage from the other tab; the tab making the change does not receive its own event. Then change one thing in the example and observe whether the event still fires.
Common Beginner Mistakes
- Expecting
storageto fire without its required user action or browser condition. - Open two tabs and update localStorage from the other tab; the tab making the change does not receive its own event.
- Adding repeated event listeners without considering cleanup or unwanted side effects.
Key Takeaways
storagereports another same-origin browsing context changes localStorage.addEventListener("storage", ...)listens for the event on the appropriate target.- Open two tabs and update localStorage from the other tab; the tab making the change does not receive its own event.