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.

JavascriptAuth Jwt

Code

javascriptsnippet
19 lines
// 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 closed

Inside 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

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`.