The BroadcastChannel API

By

Published · Updated

Tagged: Web Platform

Learn the basics of 1-to-many communication with the BroadcastChannel API: create a channel, send data with postMessage(), and listen for the message event.

The Channel Messaging API is a great way to send 1-to-1 messages from a window to an iframe, from a window to a Web Worker, and so on.

The BroadcastChannel API can be used to send 1-to-many messages, communicating to multiple entities at the same time.

The classic use case: the user logs out in one tab, and you want every other open tab of your site to log out too. Or they change the theme, or add an item to the cart, and the other tabs should update without a reload.

Create a channel

You start by initializing a BroadcastChannel object:

const channel = new BroadcastChannel('thechannel')

The name is just a string. Every BroadcastChannel created with the same name, in any tab, window, iframe or worker of the same origin, is connected to the same channel. There’s no setup step and no server: the first object creates the channel, the others join it.

You can read the name back with channel.name.

Send a message

To send a message on the channel you use the postMessage() method:

channel.postMessage('Hey!')

A message can be any of those supported values:

The data is copied using the structured clone algorithm, so the receiver gets a copy, not a reference. A Date arrives as a Date, a Map as a Map.

You can’t send functions or DOM nodes. If you try to send a function, postMessage() throws a DataCloneError:

channel.postMessage(() => {}) // DataCloneError

In practice I send a small object with a type field, so the receiver knows what happened:

channel.postMessage({ type: 'logout' })
channel.postMessage({ type: 'cart-updated', count: 3 })

Receive messages

To receive messages from the channel, listen to the message event:

channel.onmessage = (event) => {
  console.log('Received', event.data)
}

addEventListener works too, which is handy if you want more than one listener:

channel.addEventListener('message', (event) => {
  if (event.data.type === 'logout') {
    window.location.href = '/login'
  }
})

The sender doesn’t get its own message

The event is fired on every BroadcastChannel object listening to that channel, except the one that sent the message.

This is the part that confuses people when testing. If you open your page in one tab, post a message and listen on the same object, nothing happens. Open a second tab and you’ll see it arrive there.

Note that it’s the object that’s excluded, not the tab. If you create two BroadcastChannel objects with the same name in the same page, one receives what the other sends:

const a = new BroadcastChannel('demo')
const b = new BroadcastChannel('demo')

b.onmessage = (event) => console.log('b got', event.data)

a.postMessage('hello') // logs "b got hello"

If the current tab also needs to react, call your update function directly when you post. Don’t wait for the message.

Which pages can talk to each other

Only pages and workers on the same origin share channels. https://example.com can’t talk to https://other.com, and it can’t talk to http://example.com either (different protocol, so different origin).

Browsers also split channels by storage partition. Say a page on a.com embeds an iframe from b.com, and you also have a tab open on b.com. The iframe can’t talk to that tab, even though both are b.com. If the top page were on b.com too, they could.

The API is available in Web Workers, so a worker can broadcast to every tab of your app.

Handle messages that can’t be read

There’s a second event, messageerror, fired when a message arrives that can’t be deserialized:

channel.addEventListener('messageerror', (event) => {
  console.error('Could not read message', event)
})

You’ll rarely see it, but it’s cheap to add if you send binary data around.

Close the channel

You can close the channel using:

channel.close()

This disconnects the object and lets it be garbage collected. After closing, calling postMessage() on it throws an InvalidStateError, and it won’t receive anything anymore. Other objects on the same channel keep working.

If you create a channel inside a component, close it when the component goes away, so you don’t leave listeners behind.

A complete example: sync logout across tabs

const auth = new BroadcastChannel('auth')

auth.onmessage = (event) => {
  if (event.data.type === 'logout') {
    showLoggedOutScreen()
  }
}

function logout() {
  // clear the session here, then:
  auth.postMessage({ type: 'logout' })
  showLoggedOutScreen() // this tab doesn't receive its own message
}

Put this in a script that every page loads, and logging out in any tab updates all of them.

Browser support and Node.js

BroadcastChannel works in all modern browsers, and has since March 2022.

Node.js has it too, as a global, since Node 18. It’s also exported by the worker_threads module, and you can use it to talk between the main thread and worker threads.

One difference from the browser: an open channel keeps the Node process running. Call close() (or unref()) when you’re done, or your script won’t exit.

const channel = new BroadcastChannel('jobs')
channel.onmessage = (event) => console.log(event.data)

// later
channel.close()

Want me to talk about your product? You can sponsor this site.

Related posts about platform: