W3cubDocs

/Web APIs

BroadcastChannel: message event

The message event is fired on a BroadcastChannel object when a message arrives on that channel.

Syntax

Use the event name in methods like addEventListener(), or set an event handler property.

js

addEventListener("message", (event) => { })
onmessage = (event) => { }

Event type

Event properties

In addition to the properties listed below, properties from the parent interface, Event, are available.

data Read only

The data sent by the message emitter.

origin Read only

A string representing the origin of the message emitter.

lastEventId Read only

A string representing a unique ID for the event.

source Read only

A message event source, which is either a WindowProxy, a MessagePort, or a ServiceWorker object representing the message emitter.

ports Read only

An array of MessagePort objects 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

js

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

js

const channel = new BroadcastChannel("example-channel");
channel.addEventListener("message", (event) => {
  received.textContent = event.data;
});

Receiver 2

js

const channel = new BroadcastChannel("example-channel");
channel.addEventListener("message", (event) => {
  received.textContent = event.data;
});

Result

Specifications

Browser compatibility

Desktop Mobile
Chrome Edge Firefox Internet Explorer Opera Safari WebView Android Chrome Android Firefox for Android Opera Android Safari on IOS Samsung Internet
message_event 54 79 38 No 41 15.4 54 54 38 41 15.4 6.0

See also

© 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/BroadcastChannel/message_event