BroadcastChannel

Baseline 2022

Newly available

Since March 2022, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.

BroadcastChannel 接口代理了一个命名频道,可以让指定 origin 下的任意 browsing context 来订阅它。它允许同源的不同浏览器窗口,Tab 页,frame 或者 iframe 下的不同文档之间相互通信。通过触发一个 message 事件,消息可以广播到所有监听了该频道的 BroadcastChannel 对象。

备注: 此特性在 Web Worker 中可用。

构造函数

BroadcastChannel()

创建一个链接到命名频道的对象。

属性

该接口会从它的父级 EventTarget 继承属性。

BroadcastChannel.name

频道名称,返回 DOMString

事件处理程序

BroadcastChannel.onmessage

事件处理器,用于定义当该对象上触发了 message 事件时要执行的函数。

BroadcastChannel.onmessageerror

事件处理器,用于定义当该对象上触发了类型为 MessageErrorMessageEvent 事件时要执行的函数。当接收到一条无法反序列化的消息时会触发此事件。

方法

该接口会从它的父级 EventTarget 继承方法。

BroadcastChannel.postMessage()

向所有监听了相同频道的 BroadcastChannel 对象发送一条消息,消息内容可以是任意类型的数据。

BroadcastChannel.close()

关闭频道对象,告诉它不要再接收新的消息,并允许它最终被垃圾回收。

事件

message

当频道收到一条消息时触发。 也可以使用 onmessage 属性访问。

messageerror

当频道收到一条无法反序列化的消息时触发。 也可以使用 onmessageerror 属性访问。

规范

Specification
HTML Standard
# broadcasting-to-other-browsing-contexts

浏览器兼容性

BCD tables only load in the browser

参见