MessageChannel
Learn two-way communication between two ports with MessageChannel.
MessageChannel
MessageChannel sets up two-way communication between two endpoints. Creating one gives you a pair of ports: port1 and port2. A message sent from one port is received on the other. This is handy for a direct channel between the main page and a web worker.
You transfer one of the ports to the other side (for example you send channel.port2 with postMessage), then receive messages on the port you kept. This builds a one-to-one link.
MessagePort methods
Each port is a MessagePort object. The main methods are: postMessage(data) sends a message, onmessage listens for incoming ones. start opens the message queue, close closes the port.
When you transfer a port to another context (a worker, for example), the receiver must call start for messages to be processed. Assigning onmessage often starts it implicitly, but calling start explicitly is safer.
Exercise Message between two ports
Create a MessageChannel. Listen on port2: assign channel.port2.onmessage to log event.data. Send a message with port1.postMessage('hello').
Show example solution
1. Create with const channel = new MessageChannel().
2. Listen with channel.port2.onmessage = (event) => console.log(event.data).
3. Send with channel.port1.postMessage('hello').
Example solution:
const channel = new MessageChannel();
channel.port2.onmessage = (event) => {
console.log(event.data);
};
channel.port1.postMessage('hello');
Test yourself
-
When you create a MessageChannel, which two ports do you get?
- input and output
- port1 and port2
- sender and receiver
- left and right
Show answer
port1 and port2 — Correct. Creating a MessageChannel gives you two ports named port1 and port2.
-
Listen on port1
channel.port1.____= (event) => console.log(event.data);Show answer
channel.port1.onmessage= (event) => console.log(event.data); -
Match MessagePort methods
- postMessage
- Sends a message
- onmessage
- Receives a message
- start
- Starts the queue
- close
- Closes the port