MessageChannel API Basics
You'll learn how to create a dedicated two-way communication pipeline between different JavaScript contexts using the MessageChannel API.
What Is MessageChannel?
The MessageChannel API creates a pair of connected ports that can send messages to each other. Think of it like installing a private telephone line between two offices—instead of broadcasting messages to everyone, you get a direct, dedicated channel for communication.
A MessageChannel creates two MessagePort objects: port1 and port2. Messages sent on one port arrive at the other, establishing bidirectional communication.
Creating a MessageChannel
const channel = new MessageChannel();
const port1 = channel.port1;
const port2 = channel.port2;
When you instantiate MessageChannel, you immediately get two linked ports. These ports work independently but are internally connected—perfect for passing one port to a worker or iframe while keeping the other in your main script.
Using the Ports
// Listen on port1
port1.onmessage = (event) => {
console.log('Port1 received:', event.data);
};
// Send from port2
port2.postMessage('Hello from port2');
// Listen on port2
port2.onmessage = (event) => {
console.log('Port2 received:', event.data);
};
// Send from port1
port1.postMessage('Hello from port1');
Unlike direct postMessage to a worker (which goes through the worker's global scope), MessageChannel ports are dedicated endpoints you can transfer to any context, creating private communication channels.
Why Use MessageChannel?
MessageChannel shines when you need isolated, point-to-point communication—for example, allowing two workers to talk directly without routing through the main thread, or creating separate communication channels for different features.
Key Takeaway: MessageChannel creates a pair of connected ports for direct, two-way communication between JavaScript contexts, providing a dedicated pipeline independent of global messaging.