javascript / expert
Snippet
Cross-Context Communication with BroadcastChannel
BroadcastChannel provides a simple pub/sub mechanism for communication between different browsing contexts (tabs, windows, or iframes) sharing the same origin. It is ideal for synchronizing state like authentication or theme changes.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const authChannel = new BroadcastChannel('auth_sync');// When user logs out in one tabfunction logout() {authChannel.postMessage({ action: 'logout', timestamp: Date.now() });window.location.reload();}// Listening in all other tabs/windowsauthChannel.onmessage = (event) => {if (event.data.action === 'logout') {console.log('Session ended elsewhere. Redirecting...');window.location.href = '/login';}};
nextjs
Breakdown
1
new BroadcastChannel('auth_sync');
Creates or joins a communication channel with a unique name across the same origin.
2
authChannel.postMessage(...);
Sends a message object to all other active instances of this channel.
3
authChannel.onmessage = (event) => { ... };
Event handler that triggers in every tab except the one that sent the message.