Skip to content

Coordinating across tabs

Same-origin tabs are separate pages that a login, a socket or a sync loop can each touch. Coordinating them means passing messages (BroadcastChannel, the storage event), electing one tab to own shared work (Web Locks), or using a shared worker.

On this page

What it is

A user with your app open in several tabs has several pages running it, and nothing links them unless you build the link. Without it, each page acts for itself: a login or logout in one tab leaves the others stale, each tab opens its own WebSocket, and each one runs its own sync between the network and IndexedDB. Coordinating across tabs is the set of browser tools for three shapes of problem: telling the other tabs that something changed, letting a single tab do shared work while the rest wait, and giving the work a home that is not any one tab.

BroadcastChannel is the message bus. A page or worker joins a channel by constructing new BroadcastChannel(name); the first to use a name creates the channel, and anyone on the same origin (strictly, the same storage partition) who constructs the same name receives what is posted to it, with no reference to the other windows needed. postMessage() serializes the payload with the structured clone algorithm, so objects, arrays and blobs travel without hand-rolled serialization. The sender's own message listener does not fire for its own post, so the posting tab applies the change locally and then broadcasts. The specification defines no message format: the shape of what you send is yours to design. Call close() on a channel you are done with so it can be garbage collected.

The storage event is the older route. When one document writes to localStorage, a storage event fires in the other same-origin documents, including other tabs, and not in the document that wrote. The sessionStorage form reaches the iframes inside the same tab and not other tabs, so it is no use for tab-to-tab signaling.

Web Locks turn "one of us does it" into a browser primitive. navigator.locks.request(name, callback) queues a request for a named lock that is scoped to the origin; the callback runs when the lock is granted, and the lock is released when the promise the callback returns settles. The default mode is exclusive, so a single holder at a time; requests for a held lock from this tab or any other wait in a queue, and the first queued request is granted on release. Return a promise that you keep pending and the tab holds the lock for as long as it lives; practitioners who use this for leader election report that when the holding tab closes, a waiting tab is granted the lock and becomes the new leader. Options cover the rest: ifAvailable calls back with null instead of waiting when the lock is held, mode: "shared" lets several readers hold it together, steal releases the current holder's lock and preempts the queue, and signal takes an AbortSignal so a request can time out. The API is available in secure contexts (HTTPS) and in workers.

ts
type Msg =
  | { v: 1; type: 'logout' }
  | { v: 1; type: 'feed'; data: unknown };

const bus = new BroadcastChannel('app');

bus.onmessage = (e: MessageEvent<Msg>) => {
  if (e.data.v !== 1) return;          // a tab on another deploy, ignore
  if (e.data.type === 'logout') clearSession();
  if (e.data.type === 'feed') render(e.data.data);
};

function logout() {
  clearSession();                      // the sender gets no copy of its own post
  bus.postMessage({ v: 1, type: 'logout' } satisfies Msg);
}

// Whichever tab is granted the lock owns the socket; the rest wait in the queue.
void navigator.locks.request('feed-socket', () =>
  new Promise<void>(() => {
    const ws = new WebSocket('wss://example.test/feed');
    ws.onmessage = (e) => {
      const data = JSON.parse(e.data);
      render(data);                                  // this tab
      bus.postMessage({ v: 1, type: 'feed', data }); // the others
    };
    // The promise stays pending, so the lock is held until this tab goes away.
  }),
);

A SharedWorker gives the work a home outside any single tab. One worker script is reachable from several windows on the exact same origin (protocol, host and port); each page talks to it through a MessagePort from worker.port, and inside the worker each new page arrives as a connect event carrying its port. The worker stays alive while at least one page holds a reference to it, and the extendedLifetime option keeps it around briefly after the last page closes so it can flush state. Support is the catch: MDN marks SharedWorker as newly available across the latest browsers since May 2026, so older devices may lack it. A service worker can also reach its pages: self.clients.matchAll() returns the controlled clients and you call postMessage() on each; the Chrome team's write-up notes that a broadcast channel does the same fan-out in a single call.

When to use it

Broadcast when each tab should react to the same fact and can do so on its own: a login or logout, a changed theme or locale, a saved draft that other tabs should reload. Detecting a login or logout in another tab is the use the documentation itself names. Send a small message that names the event, not the whole new state; each tab already knows how to refetch.

Elect a leader when the same work would otherwise run once per tab and the server or the user would notice: one WebSocket instead of six, one token refresh, one sync loop writing IndexedDB, one notification sound. The pattern is a lock held for the life of the leader plus a channel on which the leader relays what it learns. For a short critical section, such as refreshing a token, request the lock around the refresh and let it release; a tab that was queued behind it should then read the fresh token from storage before deciding whether to refresh again. The documentation suggests shared workers for the heavier cases, such as holding a WebSocket for several tabs, where you can count on support.

When not to

Skip coordination when the tabs don't share anything worth coordinating. Two tabs editing different documents, or a marketing page that refetches on load, gain a protocol to maintain and nothing to show for it. Our advice: if a tab can simply refetch when the user returns to it and the data may be a little stale in between, do that and leave the channel out.

These tools stop at the origin. A channel is same-origin, and the lock manager treats https://example.com and https://example.org:8080 as separate worlds. To talk to an embedded iframe or popup from another origin, use window.postMessage() with an explicit target origin and check event.origin on the way in.

A browser lock is not a correctness boundary. It coordinates tabs and workers of one origin in the same browser; the same user's phone, a second browser, or a retried request after a crash is outside it. If a duplicate action would charge twice or send two emails, the server can guard it with idempotency keys or its own locks and leases, and the tab-level lock is a nicety that saves requests.

Reach for a shared worker when the simpler tools fall short, not first. The Chrome team's guidance is a broadcast channel for sending to several tabs or workers, and a shared worker for shared state, lock management or one connection for many tabs. If your audience includes older browsers or devices, check the compatibility table before betting the architecture on SharedWorker.

Compared

ToolWhat it doesReach for it whenPick something else when

BroadcastChannel

Delivers a structured-clone message to other listeners on a named channel in the same origin and storage partition

Each tab should react to a fact: logout, theme, a saved draft

The receiver is on another origin, or one tab must do the work rather than all of them

storage event

Fires in other same-origin documents when localStorage changes, not in the writer

You already persist the value in localStorage, or must support browsers without channels

You want to send an object or a one-off event; it also ties signaling to a stored string

Web Lock, short

Queues requests on an origin-scoped name; releases when the callback's promise settles

A critical section like a token refresh or an IndexedDB write should run in one tab at a time

The work is not duplicated per tab, or it must be safe across devices, which needs the server

Web Lock, held

A pending promise keeps the lock; the next queued tab is granted it when the holder closes

One tab should own a socket or a sync loop and relay to the rest

You can use a shared worker and want the work to outlive any one tab's ownership

SharedWorker

One worker reachable from several same-origin pages over message ports

Shared state or one connection, independent of which tab is open

Target browsers lack it, or a channel plus a lock already covers the need

Service worker clients.matchAll()

Lists the pages a service worker controls so it can postMessage() each

The event starts in the service worker, such as a push or a cache update

You are fanning out from a page; a channel reaches the same tabs in one call

window.postMessage()

Sends to a specific window or iframe, including across origins, with origin checks

The other party is an iframe or popup on a different origin

Everyone is on your origin; a channel needs no window references or origin checks

In a picture

requestrequestgrantedTab ALock feed-socketTab BTab A openssocket

Step 1 of 3

Two tabs ask for the same lock

Both tabs call navigator.locks.request('feed-socket', ...) with a callback that returns a pending promise. Tab A's request is granted first; Tab B's request waits in the queue. Tab A opens the WebSocket.

How to say it in an interview

The common mistake

Quiz

A tab calls bus.postMessage({ type: 'logout' }) and relies on its own onmessage handler to clear the session. What happens in that tab?
The tab holding the feed-socket lock with a pending promise is closed. What happens to the tabs whose requests are queued?
Your page embeds a payment iframe from a different origin and needs to tell it the order total changed. Which route works?
A tab wants to refresh the auth token if no other tab is already doing so, and otherwise move on at once rather than wait. Which option?

Related

Sources

  1. MDN: Broadcast Channel API
  2. MDN: Window: storage event
  3. MDN: Web Locks API
  4. MDN: SharedWorker
  5. MDN: Clients (service worker)
  6. Chrome for Developers: BroadcastChannel API - A message bus for the web
  7. Green Vitriol: Leader election in browser tabs, the easy way
Sign in to report a mistake