Frontend System Design1 min readPremium

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:

  1. Creation of a Channel:
  • You create a BroadcastChannel object by specifying a channel name. This name acts as an identifier for the communication channel.
  1. Sending Messages:
  • You can send messages using the postMessage() method of the BroadcastChannel object. This allows you to send data to all connected channels.
  1. Receiving Messages:
  • Each channel that has the same name can listen for messages using the onmessage event 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.
Premium

Keep reading with Premium

Get the rest of this guide plus every premium question, solution, and system design deep dive.

  • All premium solutions
  • System design deep dives
  • Company-specific prep

4.9/5 from our users