MessagePort

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.

* Some parts of this feature may have varying levels of support.

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

Channel Messaging APIMessagePort 接口代表 MessageChannel 的两个端口之一,它可以让你从一个端口发送消息,并在消息到达的另一个端口监听它们。

MessagePort 是一个可转移对象

EventTarget MessagePort

实例方法

继承父类 EventTarget 的方法

postMessage()

从端口发送一条消息,并且可选是否将对象的所有权交给其他浏览器上下文。

start()

开始发送该端口中的消息队列(仅在使用 EventTarget.addEventListener 时需要;使用 onmessage 已隐含调用该方法)。

close()

断开端口连接,它将不再是激活状态。

事件

继承父类 EventTarget 的事件

message

MessagePort 对象收到消息时触发。

messageerror

MessagePort 对象收到无法被反序列化的消息时触发。

示例

在下面的示例中,你可以看到一个使用 MessageChannel() 构造函数创建出的新通道。

当 IFrame 加载完成后,我们给 MessageChannel.port1 注册了一个 onmessage 回调,并且使用 window.postMessage 方法把 MessageChannel.port2 和一条消息一起传给 IFrame。

当从 IFrame 收到消息时,onMessage 函数会把消息输出到一个段落里。

js
const channel = new MessageChannel();
const output = document.querySelector(".output");
const iframe = document.querySelector("iframe");

// 等待 iframe 加载
iframe.addEventListener("load", onLoad);

function onLoad() {
  // 监听 port1 的消息
  channel.port1.onmessage = onMessage;

  // 把 port2 传给 iframe
  iframe.contentWindow.postMessage("Hello from the main page!", "*", [
    channel.port2,
  ]);
}

// 处理 port1 收到的消息
function onMessage(e) {
  output.innerHTML = e.data;
}

要查看可运行的完整示例,参考我们在 Github 上的 channel messaging 基础演示也可以在线运行)。

规范

Specification
HTML
# message-ports

浏览器兼容性

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
MessagePort
close
message event
messageerror event
postMessage
options.includeUserActivation parameter
Non-standard
start
Available in workers

Legend

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

Full support
Full support
Partial support
Partial support
No support
No support
Non-standard. Check cross-browser support before using.
See implementation notes.
Has more compatibility info.

参见