How to Sync Browser Tabs with BroadcastChannel API

The BroadcastChannel API is a built-in browser interface that enables simple, bidirectional communication between different browser contexts, such as tabs, windows, iframes, and Web Workers sharing the same origin. This article explains what the BroadcastChannel API is, demonstrates how to implement it to synchronize state across multiple tabs, and highlights its common real-world use cases.

What is the BroadcastChannel API?

The BroadcastChannel API provides a pub/sub (publish-subscribe) messaging system directly inside the browser. It allows any browsing context with the same origin (protocol, domain, and port) to broadcast messages to all other open contexts that are subscribed to the same channel name.

Unlike other cross-context communication methods like window.postMessage(), the BroadcastChannel API does not require maintaining direct references to the other windows or iframes.

How to Implement BroadcastChannel

Using the BroadcastChannel API involves three primary steps: creating or joining a channel, sending messages, and listening for incoming messages.

1. Creating a Channel

To join a communication channel, instantiate the BroadcastChannel constructor with a unique channel name:

const authChannel = new BroadcastChannel('auth_channel');

If the channel does not exist, the browser creates it. Any other tab that initializes a BroadcastChannel with the name 'auth_channel' automatically connects to the same message bus.

2. Broadcasting Messages

You can send data across the channel using the postMessage() method. The API supports any structured cloneable data, including strings, objects, and arrays:

function broadcastLogout() {
  authChannel.postMessage({
    action: 'LOGOUT',
    timestamp: Date.now()
  });
}

3. Listening for Messages

To receive broadcasts in other tabs, attach an event listener to the channel using onmessage or addEventListener('message', callback):

authChannel.onmessage = (event) => {
  const { action, timestamp } = event.data;
  
  if (action === 'LOGOUT') {
    console.log(`User logged out at ${timestamp}. Redirecting...`);
    window.location.href = '/login';
  }
};

Note: The tab that sends the message does not receive its own broadcast event.

4. Closing the Channel

When communication is no longer required, or when a component unmounts in a single-page application, close the channel to free up system resources:

authChannel.close();

Common Use Cases

BroadcastChannel vs. Alternatives