Broadcast Channel API
The Broadcast Channel API allows simple communication between browsing contexts (that is, windows, tabs, frames, or iframes) with the same origin.
1. The Concept
Unlike postMessage which requires a reference to the target window (e.g., iframe.contentWindow or window.opener), the Broadcast Channel API works like a radio station.
- Sender: Broadcasts a message on a specific channel name.
- Receivers: Any context listening to that channel name receives the message.
This is perfect for synchronizing state across tabs (e.g., logging out in one tab logs you out in all tabs).
2. Creating a Channel
To join a channel, you create a BroadcastChannel object with a specific name.
// Connect to the "app_updates" channel
const channel = new BroadcastChannel('app_updates');
3. Sending Messages
You can send any data that is supported by the structured clone algorithm (strings, objects, arrays, Blobs, etc.).
channel.postMessage('Hello from Tab 1!');
channel.postMessage({
type: 'LOGOUT',
user: 'JohnDoe'
});
4. Receiving Messages
To receive messages, listen for the message event.
channel.onmessage = (event) => {
console.log('Received:', event.data);
if (event.data.type === 'LOGOUT') {
// Perform logout logic
console.log('Logging out...');
}
};
5. Closing the Channel
When you are done, you should close the channel to allow the browser to garbage collect the object.
channel.close();
Note: This does not close the actual channel for other tabs, it just disconnects the current object from it.
programming/javascript/vanilla/javascript programming/javascript/vanilla/events programming/javascript/vanilla/web-workers programming/javascript/vanilla/service-workers-and-pwa