MessageChannel
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.
Note: This feature is available in Web Workers
Properties
-
MessageChannel.port1
Read only -
Returns port1 of the channel.
-
MessageChannel.port2
Read only -
Returns port2 of the channel.
Constructor
MessageChannel()
-
Returns a new
MessageChannel
object with two newMessagePort
objects.
Example
In the following example, you can see a new channel being created using the MessageChannel.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.
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).
Specifications
Specification |
---|
HTML Standard (HTML) # message-channels |
Browser compatibility
Desktop | Mobile | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | |
MessageChannel |
4 |
12 |
41 |
10 |
10.6 |
5 |
4.4 |
18 |
41 |
11 |
4.2 |
1.0 |
MessageChannel |
4 |
12 |
41 |
10 |
10.6 |
5 |
4.4 |
18 |
41 |
11 |
4.2 |
1.0 |
port1 |
4 |
12 |
41 |
10 |
10.6 |
5 |
4.4 |
18 |
41 |
11 |
4.2 |
1.0 |
port2 |
4 |
12 |
41 |
10 |
10.6 |
5 |
4.4 |
18 |
41 |
11 |
4.2 |
1.0 |
See also
© 2005–2021 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/MessageChannel