Course contentsShow
← Web Development
Lesson 2087 of 2,98238. JavaScript Performance in the BrowserFree lesson

Communicating with postMessage and onmessage

Sending messages to and receiving messages from workers using the message-passing API.

Communicating with postMessage and onmessage

What you'll learn: How to send data between the main thread and Web Workers using the message-passing API.

The Communication Bridge

Web Workers run in isolation from your main JavaScript thread, which means they can't directly access your page's variables or functions. Instead, they communicate by passing messages back and forth—like two people exchanging notes through a sealed door.

Sending Messages with postMessage

From your main thread, you send data to a worker using postMessage():

const worker = new Worker('worker.js');

// Send a message to the worker
worker.postMessage({ task: 'calculate', numbers: [1, 2, 3, 4, 5] });

// You can send strings, numbers, objects, arrays, etc.
worker.postMessage('Hello, worker!');

Inside your worker file, you do the reverse to send messages back:

// Inside worker.js
self.postMessage({ result: 42, status: 'complete' });

Receiving Messages with onmessage

To receive messages, you set up an onmessage handler on both sides:

// Main thread: listening for worker responses
worker.onmessage = function(event) {
  console.log('Worker said:', event.data);
  // event.data contains the actual message
};
// Inside worker.js: listening for main thread messages
self.onmessage = function(event) {
  const data = event.data;
  // Process the message and respond
  self.postMessage('Message received: ' + data);
};

The Two-Way Street Analogy

Think of it like walkie-talkies: you press the button (postMessage) to talk, then release it and listen (onmessage) for a response. The event.data property is the actual message content.

Key Takeaway: Workers communicate with the main thread through postMessage() to send data and onmessage handlers to receive it—a simple, bidirectional message-passing system that keeps threads isolated but connected.