MessagePort: Send and Receive on Dedicated Ports
You'll learn how to use MessagePort objects for bidirectional, dedicated communication channels between contexts.
The Core Idea
When you create a MessageChannel, you get two MessagePort objects that form a private communication line. Think of it like a pair of walkie-talkies: what you transmit on port1 is received on port2, and vice versa. Each port has its own postMessage() method and listens for its own 'message' events, giving you fine-grained control over bidirectional messaging.
Unlike direct postMessage() calls where you broadcast to an entire Worker or window, MessagePort creates a dedicated pipe between two specific endpoints. This is especially powerful when you want to establish multiple independent channels or pass communication rights to different parts of your code.
How MessagePort Works
Each MessagePort operates independently:
const channel = new MessageChannel();
const port1 = channel.port1;
const port2 = channel.port2;
// Set up listeners on both ports
port1.onmessage = (event) => {
console.log('Port1 received:', event.data);
};
port2.onmessage = (event) => {
console.log('Port2 received:', event.data);
port2.postMessage('Response from port2');
};
// Send from port1, receive on port2
port1.postMessage('Hello from port1');
You can transfer a MessagePort to a Worker, creating a direct channel:
const channel = new MessageChannel();
const worker = new Worker('worker.js');
worker.postMessage({ port: channel.port1 }, [channel.port1]);
channel.port2.onmessage = (e) => {
console.log('Main thread received:', e.data);
};
Key Takeaway: MessagePort objects provide dedicated, bidirectional communication pipes that can be passed between contexts, enabling complex messaging architectures beyond simple broadcast-style postMessage() calls.