FrontendPro

90Implement synchronization between browser tabs using BroadcastChannel

mediumAbout 45 minutesCodingbroadcastchannelmulti-tabstateconflict-resolution

Problem

A user opens your app in three tabs, changes the theme in one and logs out in another. Every tab should reflect both changes without a reload.

Implement createSyncedStore(channelName, initialState) on top of BroadcastChannel:

  • getState() and subscribe(listener) (returns an unsubscribe function); listeners receive the new state.
  • setState(partial) merges partial into the state, notifies local listeners, and broadcasts the change to the other tabs.
  • When a message arrives from another tab, apply it and notify local listeners, without broadcasting it again (no echo loops).
  • A tab that opens later asks the existing tabs for the current state and adopts the newest answer.
  • Concurrent updates must converge: give every change a version (a counter that is always bumped above the highest version seen, a Lamport clock) plus the tab id as a tie-breaker, and apply a remote change only if it is newer than what the tab already has.
  • close() closes the channel.
const session = createSyncedStore("session", { theme: "light", user: { name: "Asha" } });
session.subscribe((state) => applyTheme(state.theme));
logoutButton.onclick = () => session.setState({ user: null }); // every tab logs out

Try it yourself

Write your solution, run it, then submit to check it against the tests.

App.jsxReact + DOM

Step-by-step

new BroadcastChannel(channelName) connects every tab (and worker) of the same origin that uses that name. A message is delivered to every other channel object with that name, never back to the sender. Give the tab a random id, for example from crypto.randomUUID().

Unlock the full solution

What's inside

  • Step-by-step
  • Approach
  • Solution
  • Complexity
  • Edge cases
  • Follow-up questions
  • Tests

Includes 2 code listings, 5 edge cases, 4 follow-up questions.

One-time payment by UPI, card or net banking. Launch price.

All 150 answersOne payment, yours forever