BroadcastChannel: message event
MDN Web Docs · نسخهٔ df622a2a1c1e · CC BY-SA 2.5 و مجوز جداگانهٔ ناشر برای نمونهکد
{{APIRef("BroadCastChannel API")}}{{AvailableInWorkers}}
The **message** event of the {{domxref("BroadcastChannel")}} interface fires when a message arrives on that channel.
Syntax
Use the event name in {{domxref("EventTarget/addEventListener", "addEventListener()")}}:
addEventListener("message", (event) => { })Alternatively, assign to the event handler property of the interface:
onmessage = (event) => { }Event type
A {{domxref("MessageEvent")}}. Inherits from {{domxref("Event")}}.
{{InheritanceDiagram("MessageEvent")}}
Examples
In this example there's a "sender" {{HTMLElement("iframe")}} that broadcasts the contents of a {{HTMLElement("textarea")}} when the user clicks a button. There are two "receiver" iframes that listen to the broadcast message and write the result into a {{HTMLElement("div")}} element.
Sender
const channel = new BroadcastChannel("example-channel");
const messageControl = document.querySelector("#message");
const broadcastMessageButton = document.querySelector("#broadcast-message");
broadcastMessageButton.addEventListener("click", () => {
channel.postMessage(messageControl.value);
});Receiver 1
const channel = new BroadcastChannel("example-channel");
channel.addEventListener("message", (event) => {
received.textContent = event.data;
});Receiver 2
const channel = new BroadcastChannel("example-channel");
channel.addEventListener("message", (event) => {
received.textContent = event.data;
});Result
{{ EmbedLiveSample('Sender', '100%', 220) }}
{{ EmbedLiveSample('Receiver_1', '100%', 160) }}
{{ EmbedLiveSample('Receiver_2', '100%', 160) }}
Specifications
{{Specifications}}
Browser compatibility
{{Compat}}
See also
- Related events: {{domxref("BroadcastChannel/messageerror_event", "messageerror")}}.