MessageChannel:MessageChannel() 构造函数

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

MessageChannel 接口的 MessageChannel() 构造函数返回一个新的 MessageChannel 对象,其中包含两个新的 MessagePort 对象。

语法

js
new MessageChannel()

参数

无(undefined)。

返回值

一个新的 MessageChannel 对象。

示例

在以下的代码块中,你可以看到使用 MessageChannel() 构造函数创建的新 Channel。当 <iframe> 加载完成后,我们使用 MessagePort.postMessageport2 传递给 <iframe>,并附带一条消息。然后 handleMessage 处理程序响应从 <iframe> 发送回来的消息(使用 onmessage),并将其放入一个段落中。同时监听 port1 以检查何时接收到消息。

js
const channel = new MessageChannel();
const para = document.querySelector("p");

const ifr = document.querySelector("iframe");
const otherWindow = ifr.contentWindow;

ifr.addEventListener("load", iframeLoaded, false);

function iframeLoaded() {
  otherWindow.postMessage("来自主页的问候!", "*", [channel.port2]);
}

channel.port1.onmessage = handleMessage;
function handleMessage(e) {
  para.innerHTML = e.data;
}

有关完整的运行示例,请参阅我们在 GitHub 上的 channel messaging 基础示例也可以实时运行它

规范

Specification
HTML Standard
# dom-messagechannel-dev

浏览器兼容性

BCD tables only load in the browser

参见