Course contentsShow
← JavaScript
Lesson 2169 of 2,72345. Workers and ConcurrencyFree lesson

Basic PostMessage Syntax: Sender and Receiver

Understand the postMessage method signature and how to send messages from one context to another.

Basic PostMessage Syntax: Sender and Receiver

You'll learn the exact method signature for postMessage and how to structure message sending and receiving in workers.

The Core Method Signature

When you send a message from one context to another (main thread to worker, or worker to main thread), you use the postMessage method with this basic signature:

postMessage(message, [transfer])
  • message: The data you want to send (will be cloned using structured clone algorithm)
  • transfer (optional): An array of transferable objects to move ownership rather than copy

Sender Side

From the main thread sending to a worker:

const worker = new Worker('worker.js');
worker.postMessage({ task: 'calculate', value: 42 });

From inside the worker sending back to main:

// In worker.js
postMessage({ result: 84 });

Receiver Side

On the main thread listening for worker responses:

worker.addEventListener('message', (event) => {
  console.log(event.data); // { result: 84 }
});

Inside the worker listening for main thread messages:

// In worker.js
self.addEventListener('message', (event) => {
  const { task, value } = event.data;
  // Process and respond
});

The Message Event

The receiver always gets a MessageEvent object where:

  • event.data contains your actual message
  • event.origin indicates the source (for cross-window messaging)

Think of postMessage like a two-way radio: you press the button to send, then listen on a specific channel to receive. Both sides use the same method but in opposite directions.

Key Takeaway: postMessage(data) sends messages from either direction, while addEventListener('message', handler) receives them—the event.data property holds your actual message payload.