--- title: MessagePort slug: Web/API/MessagePort tags: - API - Channel messaging - HTML5 - Interface - MessagePort - NeedsTranslation - Reference - TopicStub translation_of: Web/API/MessagePort ---
{{APIRef("HTML DOM")}}
The MessagePort interface of the Channel Messaging API represents one of the two ports of a {{domxref("MessageChannel")}}, allowing messages to be sent from one port and listening out for them arriving at the other.
{{AvailableInWorkers}}
Inherits methods from its parent, {{domxref("EventTarget")}}
Inherits event handlers from its parent, {{domxref("EventTarget")}}
message is fired on the port—that is, when the port receives a message.MessagePort object receives a message.MessagePort object receives a message that can't be deserialized.In the following example, you can see a new channel being created using the {{domxref("MessageChannel.MessageChannel","MessageChannel()")}} constructor.
When the IFrame has loaded, we register an {{domxref("MessagePort.onmessage","onmessage")}} handler for {{domxref("MessageChannel.port1")}} and transfer {{domxref("MessageChannel.port2")}} to the IFrame using the {{domxref("window.postMessage")}} method along with a message.
When a message is received back from the IFrame, the onMessage function simply outputs the message to a paragraph.
var channel = new MessageChannel();
var output = document.querySelector('.output');
var 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).
| Specification | Status | Comment |
|---|---|---|
| {{SpecName('HTML WHATWG', 'web-messaging.html#message-ports','Message ports')}} | {{Spec2('HTML WHATWG')}} |
{{Compat("api.MessagePort")}}