MessageChannel.port2

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

MessageChannel接口的 port2 是一个只读属性,返回消息通道的第二个端口,该端口连接到通道另一端的上下文,也就是发送消息时的目的地。

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

语法

channel.port2;

表示通道第二个端口的一个MessagePort对象,该端口附加到通道另一端的上下文。

 

示例

如下代码所示,通过MessageChannel.MessageChannel构造函数创建了一个新的通道。当IFrame加载完毕,我们使用MessagePort.postMessage将一条消息以及port2传递给IFrame。handleMessage处理程序响应从IFrame发回的消息(使用 MessagePort.onmessage),将其放入段落中。MessageChannel.port1已经监听,以检测消息何时到达。

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
port2
Living Standard  

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

文档标签和贡献者

此页面的贡献者: ceido
最后编辑者: ceido,