β Blog Β· Web Development
BroadcastChannel API: Real-Time Chat Between Tabs, Windows, and Workers
Ever opened the same web app in two tabs and wished they could talk to each other? Thatβs exactly what the BroadcastChannel API gives you.
π What is BroadcastChannel?
Itβs a browser API that lets different execution contexts (tabs, windows, iframes, workers) from the same origin send messages to each other instantly.
No servers, no sockets, no localStorage hacksβjust direct communication inside the browser.
β‘ How it works
- Create a channel with a name
- Post a message from one context
- All contexts listening on the same channel receive it
// Tab A
const bc = new BroadcastChannel('chat');
bc.postMessage({ user: 'Alice', text: 'Hello!' });
// Tab B
const bc2 = new BroadcastChannel('chat');
bc2.onmessage = (e) => {
console.log('Got message:', e.data);
};
πΌ Diagram: Message Flow Between Contexts
ββββββββββββββββ
β Tab A β
β (sender) β
ββββββββ¬ββββββββ
β
postMessage β
βΌ
ββββββββββββββββββ
β BroadcastChannelβ
ββββββββββββββββββ
β²
onmessage β
β
ββββββββββββββ΄βββββββββββββ
β β
ββββββββββββββββ ββββββββββββββββ
β Tab B β β Worker β
β (receiver) β β (receiver) β
ββββββββββββββββ ββββββββββββββββ
Any tab, iframe, or worker subscribed to the same channel instantly gets the message.
---
π― Common Use Cases
π Sync state across tabs (e.g., log out everywhere, update shopping cart)
π Share data (charts, caching, results) so only one tab does heavy work
π‘ Leader election (pick one tab to fetch, others just listen)
π Session awareness (detect duplicate sessions, broadcast auth changes)
---
π‘ Pro Tips
Works in Web Workers and Service Workers too
Messages are broadcastβeveryone listening on the channel gets them
Not persistent: once the page is closed, the channel is gone
For larger payloads, combine with IndexedDB (store data, broadcast the key)
---
π In short: BroadcastChannel is the simplest way to make your tabs collaborate.
If youβre building apps with multiple charts, dashboards, or want βlog out everywhereβ behavior, this little API can save you a lot of complexity.