MessageChannel:port1 属性

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2015.

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

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

一个 MessagePort 对象,它是 channel 的第一个端口,即连接到发起 channel 上下文的端口。

示例

在以下的代码块中,你可以看到使用 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;
}

规范

Specification
HTML
# dom-messagechannel-port1-dev

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobileserver
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
Deno
Node.js
port1

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

参见