Broadcast channel
Learn cross-tab messaging between same-origin tabs with BroadcastChannel.
BroadcastChannel
BroadcastChannel lets same-origin tabs, windows and iframes exchange messages. A message sent from one tab is received on every other tab that has a channel with the same name. No server is needed; all traffic stays inside the browser.
You first create the channel with new BroadcastChannel('metrics'). To send a message use channel.postMessage(data), to listen use channel.onmessage. When done, close it with channel.close().
The same-origin boundary
The same-origin boundary matters: a channel only works across tabs that share protocol, host and port. http://site.com and https://site.com are different origins; messages do not cross. This is a security requirement.
The incoming message arrives in event.data. A message always goes to the other tabs; the sending tab does not receive its own message. With many tabs open, each one is a separate receiver.
Exercise Broadcast a message on the metrics channel
Create a BroadcastChannel named 'metrics'. Use postMessage to send { value: 42 }.
Show example solution
1. Create the channel with const channel = new BroadcastChannel('metrics').
2. Send the message with channel.postMessage({ value: 42 }).
Example solution:
const channel = new BroadcastChannel('metrics');
channel.postMessage({ value: 42 });
Test yourself
-
Send a message
channel.____({ value: 42 });Show answer
channel.postMessage({ value: 42 }); -
Between which tabs does BroadcastChannel work?
- Between same-origin tabs
- Between all tabs in the browser
- Only within the same tab
- Between different devices
Show answer
Between same-origin tabs — Correct. BroadcastChannel works only across same-origin tabs; this is a security boundary.
-
Match BroadcastChannel methods
- constructor
- Creates the channel
- postMessage
- Sends a message
- onmessage
- Receives a message
- close
- Closes the channel