Using JavaScript “storage” event to listen for changes across tabs

TIL there’s a storage event you can use to listen for changes in localStorage and sessionStorage.

So you can listen for changes to storage values across tabs:

// Tab 1
localStorage.setItem('example', 'tab1');
window.addEventListener('storage', () => console.log('🚀', localStorage.getItem('example')));

// Tab 2
localStorage.setItem('example', 'tab2');

// ...which logs "🚀 tab2" in Tab 1!

Note: Storage is partitioned per origin, so you can’t listen for changes across domains or subdomains.

P.S. The craziest thing about this to me is it’s literally been a thing since Chrome 1: https://developer.mozilla.org/en-US/docs/Web/API/Window/storage_event