Baseline Widely available
Note: This feature is available in Web Workers.
The MessageChannel
interface of the Channel Messaging API allows us to create a new message channel and send data through it via its two MessagePort
properties.
MessageChannel()
Returns a new MessageChannel
object with two new MessagePort
objects.
MessageChannel.port1
Read only
Returns port1 of the channel.
MessageChannel.port2
Read only
Returns port2 of the channel.
In the following example, you can see a new channel being created using the MessageChannel()
constructor.
When the IFrame has loaded, we register an onmessage
handler for MessageChannel.port1
and transfer MessageChannel.port2
to the IFrame using the window.postMessage
method along with a message.
When a message is received back from the IFrame, the onMessage
function outputs the message to a paragraph.
const channel = new MessageChannel();
const output = document.querySelector(".output");
const iframe = document.querySelector("iframe");
// Wait for the iframe to load
iframe.addEventListener("load", onLoad);
function onLoad() {
// 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 port1
function onMessage(e) {
output.innerHTML = e.data;
}
For a full working example, see our channel messaging basic demo on GitHub (run it live too).
Specifications Browser compatibility See alsoRetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.3