The Problem
Working with multiple browser tabs or Node.js processes that need to talk to each other is a pain. Sure, the native BroadcastChannel API exists, but it’s not supported everywhere (looking at you, Safari). And if you’re working in Node or some other environment like Deno, you’re completely out of luck. You need a reliable way to share messages across tabs or processes, preferably without duct-taping IndexedDB, localStorage, or WebSockets together yourself.
What This Does
The broadcast-channel library gives you a polyfill for the BroadcastChannel API that works across a ton of environments—modern browsers, old browsers, Node.js, Deno, Web Workers, even iframes. It’s like the duct tape you were about to use, but it actually works and doesn’t fall apart when you need it most.
The heavy lifting happens in the dist/es5node/ folder, where the library provides multiple implementations for message passing using various methods like indexed-db, localstorage, or even cookies if you’re feeling masochistic. If you’re in Node, it falls back to filesystem sockets, which is clever. Need to coordinate browser tabs and elect a "leader" (because everyone loves a little distributed computing)? The leader-election module has you covered.
The library isn’t just a polyfill—it’s configurable. You can force it to use specific methods ({ type: 'localstorage' }) or disable WebWorker support to squeeze out a bit of performance.
Real-World Use
Say you’re building a web app that allows users to log in across multiple tabs. You want to broadcast the login event from one tab to all others. Here’s how easy it can be:
import { BroadcastChannel } from 'broadcast-channel';
const channel = new BroadcastChannel('user-session');
// Tab 1: Broadcast login info channel.postMessage({ userId: 123, loggedIn: true });
// Tab 2: Listen for the event channel.onmessage = (msg) => { console.log(User ${msg.userId} logged in: ${msg.loggedIn}); };
It even works offline. No server round-trips, no flaky WebSocket connections. Just tabs/processes talking to each other like civilized adults.
The Bottom Line
broadcast-channel is the tool you didn’t know you needed until you were stuck hacking together message passing with localStorage or praying that BroadcastChannel worked everywhere. It’s not tiny (~25KB minified), so maybe skip it for trivial projects, but if you need reliable cross-context communication, it’s a lifesaver. Bonus points for the built-in leader election if you’re doing anything distributed.