Code

Browser Web APIs

CDEFGHIJKLMNOPQRSTUVWXYZ

Broadcast Channel API

Enables simple bidirectional communication between same-origin browsing contexts — tabs, windows, iframes, and workers — via a named channel. Any context can publish a message and all other contexts subscribed to the same channel name receive it.

MDN Reference

Key Interface — BroadcastChannel
  • new BroadcastChannel(name) — Opens a channel with the given name. All same-origin contexts using the same name are connected.
  • BroadcastChannel.postMessage(message) — Broadcasts a structured-cloneable message to all other contexts on the channel. The sender does not receive its own message.
  • BroadcastChannel.onmessage — Event handler called when a message arrives.
  • BroadcastChannel.onmessageerror — Event handler called when a message cannot be deserialized.
  • BroadcastChannel.close() — Disconnects from the channel and releases resources.
  • BroadcastChannel.name — Read-only. The name of the channel.
Example — Sync theme across tabs

When the user toggles the theme in one tab, broadcast the change so all other open tabs update instantly.

const themeChannel = new BroadcastChannel('theme-sync');

// Send theme change to all other tabs
function setTheme(theme) {
  document.documentElement.setAttribute('data-theme', theme);
  themeChannel.postMessage({ type: 'THEME_CHANGE', theme });
}

// Receive theme changes from other tabs
themeChannel.onmessage = (event) => {
  if (event.data.type === 'THEME_CHANGE') {
    document.documentElement.setAttribute('data-theme', event.data.theme);
  }
};

// Clean up when the page is unloaded
window.addEventListener('unload', () => themeChannel.close());
Example — Logout from all tabs

Broadcast a logout event so every open tab redirects to the login page when the user signs out.

const authChannel = new BroadcastChannel('auth');

// Broadcast logout
function logout() {
  clearSession();
  authChannel.postMessage({ type: 'LOGOUT' });
  location.href = '/login';
}

// Other tabs listen and redirect
authChannel.addEventListener('message', (event) => {
  if (event.data.type === 'LOGOUT') {
    location.href = '/login';
  }
});
Example — Using addEventListener
const channel = new BroadcastChannel('notifications');

channel.addEventListener('message', (event) => {
  console.log('Channel:', channel.name);
  console.log('Received:', event.data);
});

channel.addEventListener('messageerror', (event) => {
  console.error('Failed to deserialize message', event);
});

// Send a message
channel.postMessage({ text: 'Hello from tab 1', timestamp: Date.now() });

// Disconnect
channel.close();