What is BroadcastChannel API in JavaScript?
The Broadcast Channel API allows us to have
Steps to create a Communication channel:
- Create or join a Broadcast Channel
- Post the message
- Bind the
messageevent
1. Create or join a Broadcast Channel
To create or join a Broadcast Channel, create a new Broadcast Channel object with the channel name. If the channel is not available, a new channel will be created.
// Connection to a broadcast channel
const bc = new BroadcastChannel('my_channel');
2. Post the message
To send a message to a channel, use the postMessage method of the Broadcast Channel object. The message can be any object.
let msg = {
type : "settings_changed",
settings : {
mode : 'night'
}
}
bc.postMessage(msg);
3. Bind the message event
When a message is posted, a message event is dispatched to each BroadcastChannel object connected to this channel. The way this event we can handle is event is shown below.
bc.onmessage = (event) => {
let data = event.data;
if(data.type === "settings_changed"){
let settings = data.settings;
// change settings(settings);
}
}
4. Disconnect from channel
To disconnect from the connected Broadcast Channel call the close method.
// Disconnect the channel
bc.close();
The complete code
// Connection to a broadcast channel
const bc = new BroadcastChannel('my_channel');
// listen π for message
bc.onmessage = (event) => {
let data = event.data;
if(data.type === "settings_changed"){
let settings = data.settings;
// change settings(settings);
}
}
// sending a message
let msg = {
type : "settings_changed",
settings : {
mode : 'night'
}
}
bc.postMessage(msg);
// close connection
bc.close();
For Further Reading