MessageChannel: port1 属性

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 2015 年 9 月以来,该特性已在各大浏览器中可用。

注意:此功能在 Web Workers 中可用。

MessageChannel 接口的 port1 只读属性返回消息通道的第一个端口——附加到发起通道的上下文的端口。

一个 MessagePort 对象,它是通道的第一个端口,即附加到发起通道的上下文的端口。

示例

在以下代码块中,你可以看到使用 MessageChannel() 构造函数创建了一个新的通道。当 <iframe> 加载后,我们使用 MessagePort.postMessageport2 和一条消息传递给 <iframe>。然后 handleMessage 处理器响应从 <iframe> 发回的消息(使用 onmessage),并将其放入一个段落中。handleMessage 方法与 port1 相关联,以监听消息何时到达。

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

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

ifr.addEventListener("load", iframeLoaded);

function iframeLoaded() {
  otherWindow.postMessage("Hello from the main page!", "*", [channel.port2]);
}

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

规范

规范
HTML
# dom-messagechannel-port1-dev

浏览器兼容性

另见