BroadcastChannel Syncs State Across Tabs
Broadcast auth events with BroadcastChannel: one postMessage reaches every same-origin listener on the channel, delivery is asynchronous, close on teardown.
Code
// BroadcastChannel: 同源的所有上下文按频道名收发,Node 18+ 同样内建
const tabA = new BroadcastChannel('auth-session');
const tabB = new BroadcastChannel('auth-session');
// 两个「标签页」各自持有连接;B 订阅认证状态变化
tabB.onmessage = (event) => {
console.log('tab B got:', event.data.type, 'by', event.data.by);
};
// 登出动作广播一次,所有标签页各自清理本地状态
tabA.postMessage({ type: 'logout', by: 'user-42' });
// 消息跨上下文异步投递:让出事件循环后才能收到
await new Promise((resolve) => setTimeout(resolve, 10));
// 关闭连接:标签页关闭或组件卸载时调用
tabA.close();
tabB.close();
console.log('channels closed');Output
Captured from a sandboxed run of this snippet in the build pipeline.
tab B got: logout by user-42
channels closedInside the snippet
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.
Top-level bindings tabA, tabB hold the demo state — nothing sits inside a function scope.
Using it
The demo output is labeled (tab B got:, channels closed); each label names the call that printed it.
Key statements
await new Promise((resolve) => setTimeout(resolve, 10));
tabB.onmessage = (event) => {
console.log('tab B got:', event.data.type, 'by', event.data.by);
};
Interactive Tools for This Topic
Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.JWT Expiry CalculatorDecode a JWT payload and convert its exp, iat, and nbf claims into UTC ISO timestamps, with an expired-or-valid verdict.DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.Indentation ConverterConvert leading indentation between tabs and spaces at a chosen width, leaving inner content untouched.
FAQ
- Does this require external packages?
- No. It relies only on built-in language and platform APIs, so you can paste it into a project without installing anything. Its state lives in module-level bindings: `tabA`, `tabB`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.