Channel Messaging API
MessageChannel 接口的 port1 只读属性返回消息 channel 的第一个端口——即附加到发起 channel 的上下文的端口。
值
一个 MessagePort 对象,它是 channel 的第一个端口,即连接到发起 channel 上下文的端口。
示例
在以下的代码块中,你可以看到使用 MessageChannel.MessageChannel 构造函数创建的新 Channel。当 iframe 加载完成后,我们使用 MessagePort.postMessage 将 MessageChannel.port2 传递给 iframe,并附带一条消息。然后 handleMessage 处理程序响应从 <iframe> 发送回来的消息(使用 MessagePort.message_event),并将其放入一个段落中。同时监听 port1 以检查何时接收到消息。
const channel = new MessageChannel();
const para = document.querySelector("p");
const ifr = document.querySelector("iframe");
const otherWindow = ifr.contentWindow;
ifr.addEventListener("load", iframeLoaded, false);
function iframeLoaded() {
otherWindow.postMessage("来自主页的问候!", "*", [channel.port2]);
}
channel.port1.onmessage = handleMessage;
function handleMessage(e) {
para.innerHTML = e.data;
}
规范
浏览器兼容性
参见
来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。
