BroadcastChannel: message event
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since March 2022.
Note: This feature is available in Web Workers.
The message event of the BroadcastChannel interface fires when a message arrives on that channel.
Syntax
Use the event name in methods like addEventListener(), or set an event handler property.
addEventListener("message", (event) => { })
onmessage = (event) => { }
Event type
A MessageEvent. Inherits from Event.
Event properties
In addition to the properties listed below, properties from the parent interface, Event, are available.
dataRead only-
The data sent by the message emitter.
originRead only-
A string representing the origin of the message emitter.
lastEventIdRead only-
A string representing a unique ID for the event.
sourceRead only-
A message event source, which is either a WindowProxy, a
MessagePort, or aServiceWorkerobject representing the message emitter. portsRead only-
An array of
MessagePortobjects representing the ports associated with the channel the message is being sent through (where appropriate, e.g., in channel messaging or when sending a message to a shared worker).
Examples
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.
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
Specifications
| Specification |
|---|
| HTML> # event-message> |
| HTML> # handler-broadcastchannel-onmessage> |
Browser compatibility
Loading…
See also
- Related events:
messageerror.