postMessage
Learn to send messages between the main thread and the worker.
Messaging with postMessage
Data flows between the main thread and the worker through postMessage(). This method copies the value with the structured clone algorithm, so objects, arrays and maps travel safely.
worker.postMessage({ numbers: [3, 1, 2] });To reply from the worker to the main thread, call self.postMessage(). The message lands in a queue; the receiver picks it up with onmessage.
Replying with self.postMessage
To send data from the worker file back to the main thread, call self.postMessage(payload) or just postMessage(payload). self refers to the worker's global object.
self.postMessage({ sorted: [1, 2, 3] });The message does not leave instantly; it is queued and processed when the main thread is free. After heavy work finishes, you send the result back this way. console.log output inside a worker does not reach the main thread.
Exercise Send an order to the worker
Send the object { order: 42, ready: true } to the worker with postMessage.
Show example solution
worker.postMessage({ order: 42, ready: true });
Test yourself
-
How does postMessage work?
- It passes the data by reference
- It copies the data with structured clone
- It only carries strings
- It carries data synchronously
Show answer
It copies the data with structured clone — Correct! postMessage copies the data with the structured clone algorithm.
-
Send an array to the worker
worker.postMessage({ numbers: ____ });Show answer
worker.postMessage({ numbers: [5, 2, 8] }); -
postMessage matches
- worker.postMessage()
- main to worker
- self.postMessage()
- worker to main
- structured clone
- copies the data
- onmessage
- catches the message