I'm using MessageChannel() to pass messages between a page and iframe. In my scenario, the iframe is the communications initiator and the page containing it receives, transforms and responds back to the iframe.
As I was implementing the system I at first took and saved a reference to the port passed to the iframe, cached it and continue to use it for each subsequent communication.
iframe:
window.onmessage = (e) => {
console.log("iframe port established");
//using this port for all following communications
parentPort = e.ports[0];
onmessage = establishedConnectionHandler;
}
I'm running all subsequent communications from the iframe to the parent through parentPort:
parentPort.postMessage({command, guid, message});
even though the docs state that the message channel is a one-shot communication this appears to work and makes initiating communications convenient.
My question - is this supported functionality or am I exploiting undefined behavior?
Edit - I must have misunderstood the intent of the example MDN:
button.onclick = function(e) {
e.preventDefault();
var channel = new MessageChannel();
otherWindow.postMessage(textInput.value, '*', [channel.port2]);
channel.port1.onmessage = handleMessage;
function handleMessage(e) {
para.innerHTML = e.data;
textInput.value = '';
}
}
This is refactored in Kaiido's Plunker example.
That's not really clear what you are doing, even reading your code on github...
You seem to be confusing the WindowObject.postMessage method and the MessagePort's one. WindowObject's one should be used only once, at the negotiation part.
So let's take a step back to explain more basically how things should be understood:
You should think of message channels as a Yoghurt-pot Telephone® [pdf].
So to add some lines of code, what you should do is:
Generate The Yoghurt-pot telephone® a.k.a MessageChannel.
Keep one of the po(r)t and give the other one to the other user (iframe). To do this, we use the WindowObject.postMessage method, which is not the same as the one we'll use to communicate through the MessagePorts.
From the frame, receive the po(r)t and keep it tight.
From now on, each user has its own po(r)t, and only a single po(r)t. So at both ends, you need to setup listeners on their own single po(r)t.
And then when one of the two users wants to tell something to the other one, they'll do from their own po(r)t.
Fixed OP's code as a plunker.