I'm confused with postMessage
and MessageChannel
.
Here are some codes from 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;
}
I thought postMessage
method can only take two arguments, the codes above showing that it can take three, but there is nothing about the third argument of postMessage
method.
So there are my questions:
What's the meaning of the third argument of
postMessage
method?I know the usage of
MessageChannel
, but it seems to be useless, Why/When should we use MessageChannel?