这篇翻译不完整。请帮忙从英语翻译这篇文章

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

Note: 此特性在 Web Worker 中可用。

Properties

MessageChannel.port1 只读
返回channel的port1.
MessageChannel.port2 只读
返回channel的port2.

Constructor

MessageChannel()

返回一个带有两个MessagePort属性的MessageChannel新对象。

Example

在以下代码块中,您可以看到使用MessageChannel()构造函数创建的新通道。当<iframe>加载完毕,我们使用MessagePort.postMessage方法把一条消息和MessageChannel.port2传递给<iframe>。handleMessage处理程序将会从<iframe>中(使用MessagePort.onmessage监听事件)接收到信息,将数据其放入一个段落。

var channel = new MessageChannel();
var para = document.querySelector('p');
    
var ifr = document.querySelector('iframe');
var otherWindow = ifr.contentWindow;

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

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

一个完整的运行示例,可以在Github上查看 channel messaging basic demo  (run it live too).

Specifications

Specification Status Comment
HTML Living Standard
MessageChannel
Living Standard No difference from Unknown.

Browser compatibility

We're converting our compatibility data into a machine-readable JSON format. This compatibility table still uses the old format, because we haven't yet converted the data it contains. Find out how you can help!

Feature Chrome Edge Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support 4 (Yes) 41 (41) 10.0 10.6 5
Available in workers (Yes) ? 41 (41) (Yes) (Yes) (Yes)
Feature Android Chrome for Android Edge Firefox Mobile (Gecko) Firefox OS (Gecko) IE Phone Opera Mobile Safari Mobile
Basic support 4.4 4 (Yes) 41.0 (41) (Yes) 10.0 11.5 5.1
Available in workers (Yes) (Yes) ? 41.0 (41) (Yes) (Yes) (Yes) (Yes)

See also

文档标签和贡献者

此页面的贡献者: Ende93, mona, lonphy, bingou
最后编辑者: Ende93,