storage Event Fires In Other Tabs Only

The storage event reaches every same-origin page except the one that wrote, carrying key, oldValue, and newValue; a null key means another tab called clear.

JavascriptConfig Management

Code

snippet
// the storage event fires only in the "other" same-origin tabs; the writing tab itself never receives it
window.addEventListener('storage', (event) => {
  // key is null: another tab called clear()
  if (event.key === null) {
    console.log('storage cleared elsewhere');
    return;
  }
  console.log('key:', event.key, event.oldValue, '->', event.newValue);
});

// a write from this tab never triggers its own listener
localStorage.setItem('theme', 'dark');

// when another tab writes the same key, this page receives:
// key: theme null -> dark
// oldValue/newValue are strings; objects must be JSON.parse-ed by hand

Points of care

  • The package manager never enters the picture for this snippet.
  • A browser is the runtime here: window, localStorage are not available in Node.

Putting it to use

Each step the file takes is announced in the output: storage cleared elsewhere, key:.

Core lines

window.addEventListener('storage', (event) => {
  // key is null: another tab called clear()
  if (event.key === null) {
    console.log('storage cleared elsewhere');
    return;
  }
  console.log('key:', event.key, event.oldValue, '->', event.newValue);
});

Interactive Tools for This Topic

FAQ

Does storage Event Fires In Other Tabs Only run in plain Node.js?
No — it touches `window` and `localStorage`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.