Web APIsBaseline · Widely

BroadcastChannel and Web Locks API

Mental Model

BroadcastChannel delivers structured-cloned messages to every same-origin tab, iframe, and worker subscribed to a channel name. navigator.locks.request() adds an async mutex managed by the browser process that automatically releases when the callback's Promise settles or the tab crashes.

Interactive Simulator

Cross-Tab Leader Election via Web Locks + BroadcastChannel

Watch Tab 1 hold an exclusive lock while Tab 2 queues behind it and receives state updates.

Tab 1 (Lock Held)
Tab 2 (Waiting)
Step 1 / 3: 1. Tab 1 Acquires Exclusive Lock

Tab 1 calls navigator.locks.request('sync-leader', fn) and holds the lock while its Promise remains pending.

navigator.locks.request('sync-leader', async () => { /* leader */ });
Internal State / Memory
tab1Role
LEADER
tab2Role
QUEUED
lockHolder
Tab 1

Under the Hood

localStorage storage events were a leaky bulletin board; BroadcastChannel is a dedicated intercom, and navigator.locks is the physical keycard that ensures only one tab writes to OPFS or IndexedDB at a time.

  1. Origin Partitioning: Both APIs are partitioned by (origin, top-level site) in modern storage-partitioned browsers, blocking cross-site tracking.
  2. Sender Exclusion: channel.postMessage(msg) dispatches message events to other contexts on the channel, never back to the sender instance.
  3. Crash-Safe Leases: Because the browser process owns the lock table, killing a tab's renderer process immediately releases its held locks to the next queued waiter.
JS
const bus = new BroadcastChannel('auth-sync');

async function refreshSessionOnce() {
  await navigator.locks.request('auth-refresh', { ifAvailable: true }, async (lock) => {
    if (!lock) return; // Another tab already holds the refresh lock
    const token = await fetch('/api/refresh', { method: 'POST' }).then((r) => r.text());
    bus.postMessage({ type: 'TOKEN_UPDATED', token });
  });
}

Problem Genealogy

  • 2009 (localStorage storage event): Synchronous string-only cross-tab hack that failed inside workers and stalled the main thread.
  • 2016 (BroadcastChannel): Added structured-cloned async pub/sub across windows and workers.
  • 2022 (Web Locks API): Replaced brittle localStorage timestamp heartbeats with kernel-style async mutexes.

Production Pitfalls

Production Pitfall
  • Holding a lock forever for leader election: If a leader tab sleeps in bfcache while holding a lock, it can stall other tabs unless you release locks on pagehide or use AbortController.
  • Nested lock deadlocks: Acquiring lock A then B in one tab and B then A in another hangs both queues permanently; pass an AbortSignal timeout.
When Not to Use
  • When not to use BroadcastChannel: Cross-origin iframes cannot share a BroadcastChannel; use window.postMessage() with explicit targetOrigin checks instead.

Connections & Logical Next Steps

Seen in Architecture Autopsies

Mechanical Comparisons