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
- Global Authentication Sync: Logging out or expiring a session in one tab instantly triggers a logout across all other open tabs without requiring a page reload or periodic polling.
- Shopping Cart Updates: When a user adds or removes items from a cart in one tab, the cart counter and state update immediately in all other tabs.
- Theme and Preference Synchronization: Toggling dark mode or language preferences applies the new setting globally across all active sessions.
- Asset Upload Status: Displaying upload or processing progress initiated in a background tab inside the user’s active tab.
BroadcastChannel vs. Alternatives
localStorageStorage Events: While thestorageevent can synchronize tabs, it writes data to persistent storage unnecessarily, is limited to strings, and requires manual serialization.- SharedWorkers: SharedWorkers handle complex state and coordination logic across tabs, but require dedicated worker scripts and more setup. BroadcastChannel is purely for message passing and is much simpler to implement.