What is BroadcastChannel API in JavaScript?

Broadcast Channel API

The Broadcast Channel API allows us to have basic communicationi.e., sending messages between windows, tabs, frames, iframes, and workers of the same origin.

Steps to create a Communication channel:

  1. Create or join a Broadcast Channel
  2. Post the message
  3. Bind the message event

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

  1. Google developer site
  2. Mozilla Develper site
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources