0Pricing
JavaScript Academy · Lesson

Messaging with postMessage

Communicate between main thread and worker.

Messaging with postMessage is a free JavaScript Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the JavaScript Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Communicating With Messages

Because the main thread and worker have separate memory, they talk by passing messages. The postMessage method sends data; the message event receives it.

Sending to the Worker

From the main thread, call worker.postMessage(data). The data can be almost any value: numbers, strings, objects, arrays.

const worker = new Worker('worker.js');
worker.postMessage({ task: 'sum', numbers: [1, 2, 3, 4] });

Receiving in the Worker

Inside the worker, handle the message event. The sent value arrives on event.data.

// worker.js
self.onmessage = (event) => {
  const { task, numbers } = event.data;
  console.log('worker received task:', task);
};

Sending a Reply

The worker computes a result and sends it back with its own postMessage (using self or the implicit global).

// worker.js
self.onmessage = (event) => {
  const { numbers } = event.data;
  const total = numbers.reduce((a, b) => a + b, 0);
  self.postMessage(total); // send result back
};

Receiving the Reply

Back on the main thread, listen for message on the worker object to get the result.

worker.onmessage = (event) => {
  console.log('result from worker:', event.data);
};

addEventListener Style

You can use addEventListener('message', ...) instead of the onmessage property. This allows multiple listeners.

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

Structured Clone

Messages are copied using the structured clone algorithm, not shared. It handles objects, arrays, Maps, Sets, Dates, and typed arrays, but not functions, DOM nodes, or class methods.

// OK to send: numbers, strings, plain objects, arrays,
// Map, Set, Date, ArrayBuffer, typed arrays.
// NOT cloneable: functions, DOM nodes, Error stacks lost.

A Message Protocol

For multiple operations, send a type field so the worker knows what to do. This keeps a single worker flexible.

// main:
worker.postMessage({ type: 'multiply', a: 6, b: 7 });

// worker.js:
self.onmessage = (e) => {
  if (e.data.type === 'multiply') {
    self.postMessage(e.data.a * e.data.b);
  }
};

Correlating Requests

When sending many messages, attach an id so replies can be matched to their requests. The worker echoes the id back.

// main: worker.postMessage({ id: 42, value: 'x' });
// worker: self.postMessage({ id: e.data.id, done: true });
// main can now match reply id 42 to its request.

Two-Way Conversation

Messaging is bidirectional and asynchronous. The page can keep sending tasks while the worker streams back partial results, all without blocking the UI.

// Worker can report progress repeatedly:
// self.postMessage({ type: 'progress', percent: 50 });
// self.postMessage({ type: 'done', result: data });

Cleaning Up Listeners

When a worker is no longer needed, remove listeners and terminate it to avoid leaks, especially in single-page apps that create workers repeatedly.

worker.onmessage = null;
worker.terminate();

Quick Check

Test your understanding of worker messaging.

Recap

You learned worker messaging:

  • postMessage(data) sends; the message event receives.
  • Data arrives on event.data.
  • Both sides can post, making it bidirectional.
  • Data is copied via structured clone, not shared.
  • Use a type/id protocol for multiple tasks.

Next, transferable objects for zero-copy data.

Frequently asked questions

Is the “Messaging with postMessage” lesson free?

Yes — the full text of “Messaging with postMessage” is free to read here on the web, and the JavaScript Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the JavaScript Academy course, upgrade to CoddyKit PRO.

What will I learn in “Messaging with postMessage”?

Communicate between main thread and worker. You practise JavaScript Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start JavaScript Academy?

No prior experience is required. JavaScript Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Messaging with postMessage” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this JavaScript Academy lesson?

Yes. Every JavaScript Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Creating a Web Worker
  2. Messaging with postMessage
  3. Transferable Objects
  4. Use Cases and Limitations
← Back to JavaScript Academy