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 =... premium content.
