MessageChannel: port1 属性
注意:此功能在 Web Workers 中可用。
MessageChannel 接口的 port1 只读属性返回消息通道的第一个端口——附加到发起通道的上下文的端口。
值
一个 MessagePort 对象,它是通道的第一个端口,即附加到发起通道的上下文的端口。
示例
在以下代码块中,你可以看到使用 MessageChannel() 构造函数创建了一个新的通道。当 <iframe> 加载后,我们使用 MessagePort.postMessage 将 port2 和一条消息传递给 <iframe>。然后 handleMessage 处理器响应从 <iframe> 发回的消息(使用 onmessage),并将其放入一个段落中。handleMessage 方法与 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;
}
规范
| 规范 |
|---|
| HTML # dom-messagechannel-port1-dev |
浏览器兼容性
加载中…