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?
MessageChannel
is basically a 2-way communication pipe. Think of it as an alternative to window.postMessage / window.onmessage - but a somewhat easier and more configurable.
This guide explains the meaning of postMessage's 3rd parameter:
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.
P.S. I find this guide from Opera a bit easier to read than Mozilla's.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With