BroadcastChannel for same-partition contexts
Quick answer
BroadcastChannel broadcasts structured-cloneable data to other listening contexts using the same channel name and compatible storage partition. It can synchronize a preference between tabs.
How it works
Construct new BroadcastChannel(name), listen for message and call postMessage(data). The sending channel object does not receive its own message, although other matching objects in the same page can. Same origin alone may not suffice when storage partitioning differs. Messages are not persisted for later subscribers and there is no acknowledgement API. Close the channel when finished. Validate received messages and use a versioned schema; a channel name is not a security credential.
Local examples
Run in the isolated projects/realtime-lab development origin (see README). NOT RUN in local validation; expected result is instructional.
(async () => {const channel=new BroadcastChannel("v15-lab");try{console.log(channel.name);}finally{channel.close();}})()Expected console output (not executed locally):
v15-labThe name identifies the channel, not a permission boundary.
Run in the isolated projects/realtime-lab development origin (see README). NOT RUN in local validation; expected result is instructional.
(async () => {const a=new BroadcastChannel("v15-lab-two"),b=new BroadcastChannel("v15-lab-two");try{const got=new Promise(ok=>b.onmessage=e=>ok(e.data));a.postMessage({theme:"dark"});console.log(JSON.stringify(await got));}finally{a.close();b.close();}})()Expected console output (not executed locally):
{"theme":"dark"}A second channel object receives a cloned record.
Common mistakes
Do not rely on BroadcastChannel to restore durable state or send secrets to any same-origin listener.
Practice
Open two instances in the lab, send a versioned preference update and confirm the receiving instance changes its display.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
BroadcastChannel for same-partition contexts — Knowledge Check
Apply the concept and reason about local example output.
Will the sending BroadcastChannel object receive its own broadcast?
Can a new BroadcastChannel subscriber retrieve earlier broadcasts automatically?
Why may two same-origin contexts fail to communicate?
What is the expected console output of BroadcastChannel for same-partition contexts example 1?
(async () => {const channel=new BroadcastChannel("v15-lab");try{console.log(channel.name);}finally{channel.close();}})()What is the expected console output of BroadcastChannel for same-partition contexts example 2?
(async () => {const a=new BroadcastChannel("v15-lab-two"),b=new BroadcastChannel("v15-lab-two");try{const got=new Promise(ok=>b.onmessage=e=>ok(e.data));a.postMessage({theme:"dark"});console.log(JSON.stringify(await got));}finally{a.close();b.close();}})()