Events

onstorage

Another document sharing the relevant storage area modifies it. Window event handler, exposed through the body element in HTML; register on window rather than on an arbitrary element. Event interface: StorageEvent. For the described native event: bubbles: no; cancelable: no. The writing window does not receive its own event. For localStorage use same-origin contexts; sessionStorage is limited to the same top-level context. Example: Change a storage key from a second same-origin tab; this example only observes changes. The event listener is registered with addEventListener(), which avoids inline script handlers and supports multiple listeners. Inline handlers require a CSP that permits them; do not insert untrusted code into handler attributes.

Formal Syntax & Structure

html syntaxhtml
<body onstorage="handleEvent(event)">  window.addEventListener("storage", event => { /* handle event */ });

Parameters & Attributes

NameTypeDescription
onstorageJavaScript handler bodyOptional HTML event-handler code; the example uses a registered listener instead. Not a Boolean attribute.
eventStorageEventEvent object delivered to the addEventListener callback; event.type is "storage". Inspect target, currentTarget, bubbles and cancelable as appropriate.

Working Example

Example Snippethtml
<p>Window event monitor</p><p role="status" id="log">Waiting for storage</p><script>  const target = window;  const log = document.getElementById("log");  target.addEventListener("storage", event => {    log.textContent = String(event.key);  });</script>
HTML Reference