CodeBlanks Logo Icon CodeBlanks

Storage events

JavaScript course · Intermediate · Lesson 47/134

Learn to be notified when storage changes in another tab of the same origin.

The storage event

The storage event fires when localStorage changes in another tab of the same site. This lets two tabs stay in sync instantly.

window.addEventListener('storage', handler);

Important detail: the event does not fire in the same tab, only in other tabs. The tab where you call setItem does not receive it; other open tabs do.

Properties of the event object

When the event fires, the handler function receives an event object. It carries three useful properties: key gives the name of the changed key, newValue the new value, and oldValue the previous value.

window.addEventListener('storage', (event) => {
  console.log(event.key, event.newValue);
});

With these properties you can learn what changed and what the old value was.

Exercise Listen to the storage event and log details

Listen for the 'storage' event with window.addEventListener. When it fires, log event.key and event.newValue with console.log.

Show example solution
window.addEventListener('storage', (event) => {
  console.log(event.key, event.newValue);
});

Test yourself

  1. When does the storage event fire?

    // Tab A:
    localStorage.setItem('x', '1');
    // Tab B: ?
    • When localStorage changes in another tab of the same site
    • When setItem is called in the same tab
    • When the page loads
    • When the internet drops
    Show answer

    When localStorage changes in another tab of the same site — Correct! The storage event fires when another tab changes data.

  2. Listen to the storage event

    window.addEventListener('storage', ____ => { console.log(event.key); });
    Show answer
    window.addEventListener('storage', (event) => { console.log(event.key); });
  3. Match the event properties

    event.key
    Name of the changed key
    event.newValue
    The new value
    event.oldValue
    The previous value
  4. Does the storage event fire when you setItem in the same tab?

    // Single tab:
    localStorage.setItem('x', '1');
    // storage event ?
    • Yes, it fires right away
    • Only on page reload
    • Only for removeItem
    • No, it fires only in other tabs
    Show answer

    No, it fires only in other tabs — Correct! The storage event does not fire in the same tab as setItem.

All lessons in Intermediate