huachengzan huachengzan - 6 months ago 26
Javascript Question

Stuck in postMessage and MessageChannel

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:


  1. What's the meaning of the third argument of
    postMessage
    method?

  2. I know the usage of
    MessageChannel
    , but it seems to be useless, Why/When should we use MessageChannel?


Answer

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.