MessageChannel

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 中可用。

Channel Messaging APIMessageChannel 接口允许我们创建一个新的消息通道,并通过它的两个 MessagePort 属性发送数据。

构造函数

MessageChannel()

返回一个新的 MessageChannel 对象,其中包含两个新的 MessagePort 对象。

实例属性

MessageChannel.port1 只读

返回 channel 的 port1。

MessageChannel.port2 只读

返回 channel 的 port2。

示例

在以下的代码块中,你可以看到使用 MessageChannel() 构造函数创建的新 Channel。

当 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;

  // 将 port 2 传输到 iframe
  iframe.contentWindow.postMessage("来自主页的您好!", "*", [channel.port2]);
}

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

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

规范

Specification
HTML
# message-channels

浏览器兼容性

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
MessageChannel
MessageChannel() constructor
port1
port2

Legend

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

Full support
Full support
Partial support
Partial support
Has more compatibility info.

参见