Sync state across browser tabs: BroadcastChannel vs storage event vs SharedWorker

IntermediateBrowser and web interview questionBy , updated 23 November 2026

Short answer

Tabs of the same origin can talk to each other in three main ways. The storage event fires in other tabs when localStorage changes. BroadcastChannel sends any structured-cloneable message to every other tab on a named channel. A SharedWorker is one script that all tabs connect to, so it can own a single resource such as a WebSocket. For most apps, BroadcastChannel plus the Web Locks API is the right default.

The ground rules

All of these are same-origin only. https://app.example.com cannot message https://example.com this way; for that you need postMessage between windows or iframes, covered in using postMessage safely. Browsers that partition storage also keep a third-party iframe on one site separate from the same origin embedded on another site, so cross-tab messages stay within the same storage partition. See the same-origin policy for what counts as an origin.

Each tab runs its own JavaScript heap, so "syncing state" really means sending messages and letting each tab update its own copy. Decide what the source of truth is first: usually the server, sometimes localStorage or IndexedDB, and only rarely one tab.

The storage event

When one tab writes to localStorage, every other same-origin tab that shares that storage gets a storage event. The tab that made the change does not.

window.addEventListener("storage", (e) => {
  if (e.storageArea !== localStorage) return;
  if (e.key === "theme") applyTheme(e.newValue);
  if (e.key === null) resetAll(); // localStorage.clear() sends key null
});

localStorage.setItem("theme", "dark"); // other tabs hear this, this tab does not

The event carries key, oldValue, newValue and the url of the page that wrote it. It has real limits:

  • Values are strings only, so everything goes through JSON.stringify.
  • Writing the same value again fires nothing, because nothing changed. To send a repeated signal, such as "log out" twice, include a timestamp or id.
  • localStorage is synchronous and blocks the main thread, so it suits small values.
  • sessionStorage is per tab, so it does not sync across tabs at all.

It works well when the value should also persist: a theme, a feature flag, a guest cart. Practise the pattern in useLocalStorage with serialisation and cross-tab sync. For when to reach for IndexedDB instead, see localStorage vs IndexedDB.

BroadcastChannel

BroadcastChannel is a message bus with no storage side effect. Any context of the same origin (tabs, iframes, dedicated workers, service workers) can join a channel by name.

const channel = new BroadcastChannel("auth");

channel.onmessage = (e) => {
  if (e.data.type === "logout") clearSessionAndRedirect();
  if (e.data.type === "token") setAccessToken(e.data.token);
};

function logoutEverywhere() {
  channel.postMessage({ type: "logout" });
  clearSessionAndRedirect(); // the sender's own channel object does not receive its message
}

Messages use the structured clone algorithm, so objects, arrays, Map, Date and Blob arrive intact without manual serialising. Functions and DOM nodes cannot be sent. Delivery is asynchronous and there is no history: a tab that opens later sees nothing that was sent before it joined. So pair it with a store that new tabs read on startup. Call close() when a component that opened the channel is removed. It has been supported in every major browser since 2022.

The coding question Implement synchronisation between browser tabs using BroadcastChannel adds conflict handling on top.

SharedWorker

A SharedWorker is a single worker instance that every same-origin tab with the same script URL and name connects to. Each tab talks to it through a MessagePort.

// shared.js
const ports = new Set();
let socket;

onconnect = (e) => {
  const port = e.ports[0];
  ports.add(port);
  socket ??= new WebSocket("wss://example.com/live");
  socket.onmessage = (msg) => ports.forEach((p) => p.postMessage(msg.data));
  port.onmessage = (msg) => socket.send(msg.data);
};

// in each tab
const worker = new SharedWorker("/shared.js", { name: "live" });
worker.port.onmessage = (e) => render(e.data);

The appeal is one WebSocket, one cache or one sync engine for all tabs, with no election needed. The catches are worth stating honestly in an interview:

  • Support. Desktop Chrome, Edge, Firefox and Safari 16 and later support it. Chrome on Android kept it disabled for years and only started shipping it around Chrome 148, in 2026, and the operating system can kill the worker under memory pressure there. Check current support data before relying on it, and keep a fallback.
  • No close event. The worker is not told when a tab goes away, so the ports set above leaks. Have tabs send a goodbye on pagehide and prune ports that stop answering a heartbeat.
  • Debugging happens in a separate inspector (chrome://inspect/#workers in Chrome), which is easy to forget.

A worker overview is in what are Web Workers.

Leader election with Web Locks

When you want one tab to own a connection but cannot rely on SharedWorker, elect a leader tab. The Web Locks API makes this short: a lock is held by one tab at a time and released automatically when that tab closes or crashes.

navigator.locks.request("live-socket-leader", async () => {
  const socket = openSocket();
  socket.onmessage = (m) => channel.postMessage(m.data); // relay to followers
  await new Promise(() => {}); // hold the lock for the life of this tab
});

Every tab calls request. One gets the lock and becomes leader; the others wait in the queue. When the leader closes, the next tab in the queue gets the lock and opens the socket. Followers receive data over BroadcastChannel and send outgoing messages the same way for the leader to forward. Work through the edge cases in Elect one leader tab to own the WebSocket and build the API itself in Implement the Web Locks API.

Choosing one

Need Use
Small value that should also persist localStorage and the storage event
Notify other tabs of an event (logout, new data, cart change) BroadcastChannel
One shared connection or cache, desktop-first SharedWorker, with a fallback
One shared connection, everywhere Web Locks leader plus BroadcastChannel
Coordinate token refresh so it happens once Web Locks around the refresh call

Common uses: logging out every tab at once, refreshing an access token in one tab and sharing it (the rotation problem in the SPA authentication design), keeping unread badges in step, and holding one WebSocket instead of one per tab, as discussed in the real-time updates guide.

Follow-up questions interviewers ask

Why does the storage event not fire in the tab that wrote the value?

The specification sends it to other documents sharing the storage area, on the basis that the writing tab already knows. If the writing tab needs the same handling, call it directly after setItem.

What happens to messages sent while a tab is in the background or the back/forward cache?

A background tab still receives BroadcastChannel messages, though timers may be throttled. A page frozen in the back/forward cache does not run, so on pageshow with persisted true, re-read the source of truth instead of trusting missed messages.

Could a service worker do this instead?

Yes. A service worker can find open tabs with clients.matchAll() and postMessage to each. But the browser stops idle service workers after a short time, so it cannot hold a long-lived socket. It suits relaying events triggered by push or fetch.

How do you avoid two tabs overwriting each other's changes?

Give updates a version or timestamp and ignore older ones, or send operations ("add item 42") instead of whole snapshots. For anything important, let the server be the source of truth and have tabs refetch.

Mistakes to avoid

  • Expecting sessionStorage changes to reach other tabs

  • Writing the same localStorage value to send a repeated signal

  • Assuming a new tab can read old BroadcastChannel messages

  • Relying on SharedWorker without a fallback for mobile

  • Opening one WebSocket per tab for a heavy stream when one leader could relay it

Practise it in code

Interviewers rarely stop at the definition. These questions open in an editor with tests.

  1. Implement synchronization between browser tabs using BroadcastChannelMedium45 min
  2. Implement useLocalStorage() with serialization and cross-tab updatesMedium35 min
  3. Elect one leader tab to own the WebSocket: Web Locks, a broadcast relay, re-election and logoutHard50 min
  4. Implement the Web Locks API: exclusive and shared modes, ifAvailable, steal, AbortSignal and query()Hard55 min
  5. Design SPA authentication: OAuth PKCE, token storage, refresh rotation and multi-tab refreshHard60 min
  6. Design a notification system: in-app and push, with badge counts synced across tabs and devicesHard60 min