intermediate
BroadcastChannel
Coordinate same-origin tabs and windows through message channels for logout, cache invalidation, and collaboration.
BroadcastChannel provides simple same-origin messaging between tabs, windows, frames, and workers. It is useful for logout propagation, cache invalidation, theme sync, and lightweight coordination. Messages are not durable and do not cross origins, so critical workflows still need server-backed truth or persistent storage.
const channel = new BroadcastChannel('session');
channel.postMessage({ type: 'logout' });
channel.onmessage = (event) => {
if (event.data.type === 'logout') clearClientState();
};
Close channels when contexts tear down. Do not send secrets or large payloads — any same-origin script can listen.
On interviews: distinguish cross-tab notification from reliable distributed state synchronization.
Common pitfalls: using it for durable queues loses messages when contexts close. Sensitive payloads still run in exposed client contexts.
The trade-off is convenience versus control — pick the mechanism that matches your coupling and performance budget.
Checklist:
- Same-origin coordination only.
- Small, versioned message shapes.
- Close channels on teardown.
- Pair with server truth for critical state.