Broadcast Channels Explained
BroadcastChannel is a Web API that provides a simple way for different windows or tabs from the same origin to communicate with each other. It allows you to send messages between different browsing contexts, such as different tabs or windows of the same browser. MDN’s BroadcastChannel reference documents the full API.
Here’s how it works:
- Creation of a Channel:
- You create a
BroadcastChannelobject by specifying a channel name. This name acts as an identifier for the communication channel.
- Sending Messages:
- You can send messages using the
postMessage()method of theBroadcastChannelobject. This allows you to send data to all connected channels.
- Receiving Messages:
- Each channel that has the same name can listen for messages using the
onmessageevent handler.
BroadcastChannel API Example Usage:
Let’s say you have two tabs open in your browser, and you want to enable communication between them using a BroadcastChannel.
Tab 1 (Sender):
const channel = new BroadcastChannel('myChannel'); document.querySelector('button').addEventListener('click', () => { const message = document.querySelector('input').value; channel.postMessage(message); });
In this example, we create a new BroadcastChannel named ‘myChannel’. When the button is clicked, it sends the value of an input field as a message through the channel.
Tab 2 (Receiver):
const channel = new BroadcastChannel('myChannel'); channel.onmessage = function(event) { const message = event.data; console.log('Received message:', message); };
In this example, we create a BroadcastChannel with the same name (‘myChannel’). We then listen for messages using the onmessage event handler. When a message is received, we extract the data from the event and log it to the console.
How it Works:
- When Tab 1 sends a message using
channel.postMessage(message), Tab 2 receives it throughchannel.onmessage. - Both tabs use the same channel name (‘myChannel’) to establish a connection.
- Any message sent through the channel is received by all listening channels with the same name.
Important Considerations:
- The communicating tabs need to be from the same origin (i.e., same protocol, domain, and port) due to same-origin policy restrictions.
- Messages sent through a
BroadcastChannelare serialized, so they should be JSON-serializable data. - Channels persist as long as at least one script holds a reference to them. When all references are released, the channel is closed.
BroadcastChannel is useful for scenarios where you need real-time communication between different browsing contexts within your web application, such as multiplayer games, collaborative tools, or any situation where you want to sync data across multiple windows or tabs.
