Note: This feature is available in Web Workers.
The message event of the BroadcastChannel interface fires when a message arrives on that channel.
Use the event name in methods like addEventListener(), or set an event handler property.
addEventListener("message", (event) => { })
onmessage = (event) => { }A MessageEvent. Inherits from Event.
In this example there's a "sender" <iframe> that broadcasts the contents of a <textarea> when the user clicks a button. There are two "receiver" iframes that listen to the broadcast message and write the result into a <div> element.
const channel = new BroadcastChannel("example-channel");
const messageControl = document.querySelector("#message");
const broadcastMessageButton = document.querySelector("#broadcast-message");
broadcastMessageButton.addEventListener("click", () => {
channel.postMessage(messageControl.value);
});const channel = new BroadcastChannel("example-channel");
channel.addEventListener("message", (event) => {
received.textContent = event.data;
});const channel = new BroadcastChannel("example-channel");
channel.addEventListener("message", (event) => {
received.textContent = event.data;
});messageerror.