The MessagePort interface of the Channel Messaging API represents one of the two ports of a MessageChannel, allowing messages to be sent from one port and listening out for them arriving at the other.
When a message is received back from the IFrame, the onMessage function outputs the message to a paragraph.
js
const channel =newMessageChannel();const output = document.querySelector(".output");const iframe = document.querySelector("iframe");// Wait for the iframe to load
iframe.addEventListener("load", onLoad);functiononLoad(){// Listen for messages on port1
channel.port1.onmessage = onMessage;// Transfer port2 to the iframe
iframe.contentWindow.postMessage("Hello from the main page!","*",[
channel.port2,]);}// Handle messages received on port1functiononMessage(e){
output.innerHTML = e.data;}