我对 postMessage
和 MessageChannel
感到困惑。
以下是来自 MDN 的一些代码:
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;
}
我以为postMessage
方法只能接受两个参数,上面的代码显示它可以接受三个,但是没有关于postMessage
方法的第三个 参数。
所以有我的问题:
postMessage
方法的第三个参数是什么意思?我知道
MessageChannel
的用法,但是好像没什么用,为什么/什么时候应该使用MessageChannel?
最佳答案
MessageChannel
基本上是一个双向通信管道。将其视为 window.postMessage/window.onmessage 的替代品 - 但更简单且更可配置。
This guide解释postMessage的第三个参数的含义:
An object, the ownership of which is transferred to the receiving browsing context. In this case, we are transferring MessageChannel.port2 to the IFrame, so it can be used to receive the message from the main page.
附言我找到 this guide from Opera比 Mozilla 的更容易阅读。
关于javascript - 卡在 postMessage 和 MessageChannel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37539941/