We're looking for a user researcher to understand the needs of developers and designers. Is this you or someone you know? Check out the post: https://mzl.la/2IGzdXS

MessageChannel.port1

MessageChannel 的只读属性 port1 返回消息通道的第一个端口, 此端口连接到源上下文通道。

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

语法

channel.port1;

Value

一个 MessagePort 对象, 通道的第一个端口,此端口连接到源上下文通道。

示例

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

规范

规范 状态 备注
HTML Living Standard
port1
Living Standard No difference from Unknown.
Unknown
port1
Unknown W3C version of the spec

浏览器兼容性

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)

参考

文档标签和贡献者

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