Share
Broadcast Channel API allows basic communication between browsing contexts.
This API allows the communication of messages or data from different browsing contexts on the same origin.
The browsing contexts include windows, tabs, iframes, workers, etc.
The BroadcastChannel
class is used to create or join a channel.
const politicsChannel = new BroadcastChannel("politics")
politics
will be the name of the channel. Any context that initializes the BroadcastChannel
constructor with politics
will join the politics
channel. It will receive any messages sent on the channel and can send a message into the channel.
If it is the first to BroadcastChannel
constructor with politics
, the channel will be created.
To post to a channel, use the BroadcastChannel.postMessage
API.
To subscribe to a channel (to listen for messages), use the BroadcastChannel.onmessage
event.
To demonstrate the usage of Broadcast Channel, I built a simple chat app:
<body>
<header>
<h2>Web APIs<h2>
</header>
<div>
<div>
<div>
Demo - BroadcastChannel
</div>
<div>
<div>Open this page in another <i>tab</i>, <i>window</i> or <i>iframe</i> to chat with them.</div>
<div id="error"></div>
<div id="displayMsg">
</div>
<div>
<input id="input" type="text" placeholder="Type your message" />
<button onclick="sendMsg()">Send Msg to Channel</button>
</div>
</div>
</div>
</div>
</body>
<script>
const l = console.log;
try {
var politicsChannel = new BroadcastChannel("politics")
politicsChannel.onmessage = onMessage
var userId = Date.now()
} catch(e) {
error.innerHTML = "BroadcastChannel API not supported in this device."
error.classList.remove("close")
}
input.addEventListener("keydown", (e) => {
if(e.keyCode === 13 && e.target.value.trim().length > 0) {
sendMsg()
}
})
function onMessage(e) {
const {msg,id}=e.data
const newHTML = "<div><span><i>"+id+"</i>: "+msg+"</span></div>"
displayMsg.innerHTML = displayMsg.innerHTML + newHTML
displayMsg.scrollTop = displayMsg.scrollHeight
}
function sendMsg() {
politicsChannel.postMessage({msg:input.value,id:userId})
const newHTML = "<div><span><i>Me</i>: "+input.value+"</span></div>"
displayMsg.innerHTML = displayMsg.innerHTML + newHTML
input.value = ""
displayMsg.scrollTop = displayMsg.scrollHeight
}
</script>
I began by setting up the UI view. It’s a simple text and button. Type in your message and press the button to send the message.
In the scripts section, I initialize politicsChannel
and set an on-message event listener on politicsChannel
so it will receive and display the messages.
The sendMsg
function is called by the button. It sends the message to politicsChannel
via the BroadcastChannel#postMessageAPI
. Any tab, iframe, or worker that initializes this same script will receive the messages sent from here, and so this page will receive the messages sent from the other context.