MessageChannel:port2 属性
注意:此功能在 Web Workers 中可用。
port2 是 MessageChannel 接口的只读属性,它返回消息通道的第二个端口——连接到通道另一端上下文的端口,消息最初发送到该端口。
值
一个 MessagePort 对象,表示通道的第二个端口,即连接到通道另一端上下文的端口。
示例
在以下代码块中,你可以看到使用 MessageChannel() 构造函数创建了一个新的通道。当 IFrame 加载完成后,我们使用 Window.postMessage() 将 port2 以及一条消息传递给 IFrame。然后,handleMessage 处理器响应从 IFrame 发回的消息(使用 onmessage),将其放入一个段落中。port1 被监听以检查消息何时到达。
js
const channel = new MessageChannel();
const para = document.querySelector("p");
const ifr = document.querySelector("iframe");
const otherWindow = ifr.contentWindow;
ifr.addEventListener("load", iframeLoaded);
function iframeLoaded() {
otherWindow.postMessage("Hello from the main page!", "*", [channel.port2]);
}
channel.port1.onmessage = handleMessage;
function handleMessage(e) {
para.innerHTML = e.data;
}
有关完整的工作示例,请参阅 GitHub 上的 通道消息传递基本演示(也可以在线运行)。
规范
| 规范 |
|---|
| HTML # dom-messagechannel-port2-dev |
浏览器兼容性
加载中…