What is the Broadcast Channel API

· Category: JavaScript & Web

Short answer

The Broadcast Channel API lets pages from the same origin send messages to each other across browser tabs and windows without using the server as a relay.

Details

Create a channel by name and listen for messages:

const channel = new BroadcastChannel('app_sync');
channel.postMessage({ type: 'logout' });
channel.onmessage = (event) => {
  if (event.data.type === 'logout') handleLogout();
};

This is useful for synchronizing login state, theme changes, or cart updates across tabs. Because events fire asynchronously, handling them with async/await or promises keeps code readable. If you store shared state in local variables, remember that JavaScript closures can capture stale data unless you refresh references inside the handler. Broadcast Channel is simpler than localStorage polling and avoids storage events leaking to unrelated contexts.

Tips

  • Always call channel.close() when the page unloads to free resources.
  • Validate message structures before acting on them to prevent spoofing from compromised extensions.
  • Feature-detect with if ('BroadcastChannel' in window) before using it.