← 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

  1. Create a channel with a name
  2. Post a message from one context
  3. 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.
JavaScriptBroadcast Channel APIWeb Worker