Communicating with postMessage
You'll learn how to send data back and forth between your main thread and a Web Worker using the postMessage method.
The Core Idea
Once you've created a Web Worker, you have two separate JavaScript environments running: the main thread (your page) and the worker thread. They can't directly access each other's variables or functions. Instead, they communicate by sending messages—like two people passing notes under a door.
The postMessage method is how you send these "notes." Both sides can use it, making communication bidirectional. The receiving side listens with an onmessage event handler.
How It Works
From the main thread to the worker:
// main.js
const worker = new Worker('worker.js');
// Send a message to the worker
worker.postMessage('Hello from main thread!');
worker.postMessage({ task: 'calculate', value: 42 });
Inside the worker, receiving messages:
// worker.js
onmessage = function(event) {
console.log('Worker received:', event.data);
// Send a message back to main thread
postMessage('Got it! Processing...');
};
Main thread receiving responses:
// main.js
worker.onmessage = function(event) {
console.log('Main thread received:', event.data);
};
What Gets Sent
The data you pass to postMessage is copied (using the structured clone algorithm), not shared. You can send strings, numbers, objects, arrays—most common data types. Both sides get their own independent copy.
Key Takeaway: Use postMessage on both the worker and main thread to send messages, and handle incoming messages with onmessage event handlers—this creates a two-way communication channel between isolated JavaScript environments.