BroadcastChannel: message event

当频道收到一条消息时,会在关联的 BroadcastChannel 对象上触发 message 事件。

Bubbles No
Cancelable No
Interface MessageEvent
Event handler property onmessage

示例

实时示例

在这个例子中,有一个 <iframe> 作为发送者,当用户点击按钮之后,会广播 <textarea> 中的内容。同时,有两个 <iframe> 作为接收者,会监听广播的消息,并将结果写入 <div> 元素。

发送者

const channel = new BroadcastChannel('example-channel');
const messageControl = document.querySelector('#message');
const broadcastMessageButton = document.querySelector('#broadcast-message');

broadcastMessageButton.addEventListener('click', () => {
    channel.postMessage(messageControl.value);
})

接收者 1

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

接收者 2

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

结果

规范

规范 状态
HTML Living Standard Living Standard

浏览器兼容性

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
message eventChrome Full support 54Edge ? Firefox Full support 38IE No support NoOpera Full support 41Safari No support NoWebView Android Full support 54Chrome Android Full support 54Firefox Android ? Opera Android Full support 41Safari iOS No support NoSamsung Internet Android Full support 6.0

Legend

Full support  
Full support
No support  
No support
Compatibility unknown  
Compatibility unknown

相关信息