MessageChannel.port1
MessageChannel
的只读属性 port1
返回消息通道的第一个端口,此端口连接到源上下文通道。
备注: 此特性在 Web Worker 中可用
语法
channel.port1;
Value
一个 MessagePort
对象,通道的第一个端口,此端口连接到源上下文通道。
示例
在以下代码块中,你可以看到使用 MessageChannel()
构造函数创建的新通道。当 <iframe>
加载完毕,我们使用 MessagePort.postMessage
(en-US) 方法把一条消息和 MessageChannel.port2
传递给 <iframe>
。handleMessage 处理程序将会从 <iframe> 中(使用 MessagePort.onmessage
监听事件)接收到信息,将数据其放入一个段落。handleMessage 方法关联到 port1 用于监听收到的消息。
js
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).
规范
Specification |
---|
HTML Standard # dom-messagechannel-port1-dev |
浏览器兼容性
BCD tables only load in the browser