Sync state across same-origin tabs with postMessage, structured clone data, no self-delivery, and close() cleanup
0 / 5 completed
1 / 5
What does the BroadcastChannel API enable?
BroadcastChannel:const bc = new BroadcastChannel('app'). Any same-origin context that opens the same channel name can bc.postMessage(data) and others receive it via bc.onmessage. It is ideal for syncing state — like logout or theme changes — across multiple open tabs of your site.
2 / 5
Does a context receive its own messages on a BroadcastChannel?
No self-delivery: when you call bc.postMessage(), the message is delivered to all other contexts subscribed to that channel name, but not back to the sender itself. This avoids infinite loops when each tab both broadcasts and listens, so you do not need to filter out your own messages.
3 / 5
What kind of data can be sent over a BroadcastChannel?
Structured clone: BroadcastChannel uses the structured clone algorithm, so you can post objects, arrays, Map, Set, ArrayBuffer, Blob, and more without manual JSON serialisation. Non-cloneable values like functions, DOM nodes, or class instances with methods will throw a DataCloneError.
4 / 5
How is a BroadcastChannel properly cleaned up?
close():bc.close() disconnects that context from the channel. Until closed, the channel keeps the context subscribed and can prevent garbage collection of associated handlers. In component frameworks, call close() in the teardown/unmount phase to prevent memory leaks and stale listeners.
5 / 5
How does BroadcastChannel compare to using localStorage events for tab sync?
BroadcastChannel vs storage events: the storage event fires in other tabs when localStorage changes, conveying string keys/values — a workaround for cross-tab messaging. BroadcastChannel is explicit, supports structured clone data, does not persist anything to disk, and avoids overloading storage purely to trigger events.