Script Valley
JavaScript in the Browser: DOM, Events & APIs
Browser Storage and State ManagementLesson 5.3

The storage event: syncing data across browser tabs

storage event, cross-tab communication, event.key, event.newValue, event.oldValue, event.storageArea, BroadcastChannel API

The storage Event

The storage event fires on window in every tab of the same origin when localStorage changes — except the tab that made the change. This makes it useful for cross-tab communication.

window.addEventListener('storage', (e) => {
  console.log('Key changed:', e.key);
  console.log('Old value:', e.oldValue);
  console.log('New value:', e.newValue);

  if (e.key === 'theme') {
    document.body.className = e.newValue;
  }
});

Practical Use: Logout Sync

// In any tab, when user logs out:
localStorage.setItem('logout', Date.now().toString());

// In all other tabs:
window.addEventListener('storage', (e) => {
  if (e.key === 'logout') window.location.href = '/login';
});

BroadcastChannel — Direct Tab Messaging

For richer cross-tab communication, use BroadcastChannel. It works independently of localStorage.

const ch = new BroadcastChannel('app-channel');
ch.postMessage({ type: 'THEME_CHANGE', theme: 'dark' });
ch.onmessage = (e) => applyTheme(e.data.theme);

Up next

Building a simple client-side state manager with localStorage

Sign in to track progress