JavaScript Worker postMessage() Method

Beginner
⏱️ 12 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Baseline Widely available
Instance method

What You’ll Learn

The postMessage() method of Worker sends a message to the worker. Data is copied with the structured clone algorithm (or ownership can be transferred for buffers). Learn one-payload messages, arrays of values, replies via onmessage, and ArrayBuffer transfer—with five examples and try-it labs.

01

Kind

Instance method

02

Returns

undefined

03

Sends

structured clone

04

Optional

transfer list

05

Reply

worker postMessage

06

Status

Baseline widely

Introduction

After you create a worker with new Worker(), you talk to it with messages. From the main thread call worker.postMessage(data). Inside the worker, listen with self.onmessage (or addEventListener("message")) and read event.data.

The worker answers with self.postMessage(...). That is a different method on the worker global scope, but the idea is the same: clone (or transfer) data across the thread boundary.

💡
Beginner tip

You send one payload per call. Need two numbers? Send [a, b] or { a, b }—not two separate arguments like a normal function.

Understanding Worker.postMessage()

An instance method that queues a message for the worker. The first argument is mandatory and becomes event.data in the worker’s message event.

  • message — any structured-cloneable value (required; use null / undefined if empty).
  • transfer — optional array of transferable objects to move (not copy).
  • options.transfer — same meaning in the object form of the call.
  • Return value — none (undefined).
  • Baseline Widely available on MDN (since July 2015); available in Web Workers except Service Workers.

📝 Syntax

JavaScript
postMessage(message)
postMessage(message, transfer)
postMessage(message, options)

Parameters

ParameterMeaning
messageData delivered as event.data (required)
transferOptional array of transferable objects
options.transferSame as transfer in object form

Return value

None (undefined).

Typical pattern

JavaScript
const worker = new Worker("worker.js");

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

worker.postMessage([first.value, second.value]);

⚡ Quick Reference

GoalCode / note
Send dataworker.postMessage(value)
Multiple valuesworker.postMessage([a, b])
Empty pingworker.postMessage(null)
Transfer bufferworker.postMessage(buf, [buf])
Listen for replyworker.onmessage = (e) => …
MDN statusBaseline Widely available (since July 2015)

🔍 At a Glance

Four facts to remember about Worker.postMessage().

Direction
main→worker

Send to worker

Payload
one

Use array/object

Copy
clone

Or transfer

Baseline
widely

Since Jul 2015

Examples Gallery

Examples follow MDN Worker: postMessage(). Labs use blob workers so they run in one HTML file.

📚 Getting Started

Send a value and read the worker reply.

Example 1 — Send a String and Get an Echo

Main posts; worker replies with prefixed text.

JavaScript
worker.onmessage = (e) => console.log(e.data);
worker.postMessage("hello");
// worker: self.onmessage = (e) => self.postMessage("echo: " + e.data);
Try It Yourself

How It Works

The string is cloned into the worker; the reply is cloned back to main.

Example 2 — Send Multiple Values in One Array (MDN Idea)

postMessage takes one object—pack values in an array.

JavaScript
worker.postMessage([first.value, second.value]);
// worker: const [a, b] = e.data; self.postMessage(Number(a) + Number(b));
Try It Yourself

How It Works

Matches MDN’s form-input pattern: one message, two values.

📈 Clone, Transfer & Empty Pings

Objects, ArrayBuffer transfer, and mandatory message args.

Example 3 — Structured Clone of a Plain Object

Nested data is copied; the worker gets its own object graph.

JavaScript
worker.postMessage({ user: "Ada", scores: [10, 20] });
// worker returns: e.data.user + " total=" + sum(e.data.scores)
Try It Yourself

How It Works

Changing the object on main after send does not change the worker’s copy.

Example 4 — Transfer an ArrayBuffer (MDN Idea)

After transfer, the sender’s byteLength becomes 0.

JavaScript
const buf = new ArrayBuffer(8);
console.log(buf.byteLength); // 8
worker.postMessage(buf, [buf]);
console.log(buf.byteLength); // 0 — ownership moved
// worker can transfer it back the same way
Try It Yourself

How It Works

Transfer is zero-copy and fast for large buffers—but the original becomes unusable.

Example 5 — Pass null Explicitly

The message argument is required; use null for a ping with no payload.

JavaScript
worker.postMessage(null); // not worker.postMessage()
// worker: self.postMessage("pong");
Try It Yourself

How It Works

MDN: if the data is unimportant, pass null or undefined explicitly.

🚀 Common Use Cases

  • Send form values or job parameters to a background worker.
  • Ship large typed arrays / images with transfer for performance.
  • Request/response protocols (id + payload in one object).
  • Ping a worker to confirm it is alive (postMessage(null)).
  • Teaching structured clone vs shared memory / transfer.

🔧 How It Works

1

You call postMessage

Main thread passes a message (and optional transfer list).

Call
2

Clone or transfer

Data is structured-cloned, or transferables move ownership.

Copy
3

Worker event loop

A message task is queued; onmessage handlers run with event.data.

Queue
4

Optional reply

Worker may self.postMessage back to main the same way.

📝 Notes

  • MDN: Baseline Widely available (since July 2015) — no Deprecated / Experimental / Non-standard banner.
  • Available in Web Workers except Service Workers.
  • Message argument is mandatory.
  • Functions and DOM nodes are not structured-cloneable.
  • Related learning: Worker(), addEventListener(), JavaScript hub.

Universal Browser Support

Worker.postMessage() is marked Baseline Widely available on MDN (since July 2015). Logos use the shared browser-image-sprite.png sprite from this project. It is available in Web Workers except Service Workers.

Baseline · Widely available

Worker.postMessage()

Sends a structured-clone message to a dedicated worker; optional transfer moves buffer ownership.

Universal Widely available
Google Chrome Full support · Desktop & Mobile
Full support
Mozilla Firefox Full support · Desktop & Mobile
Full support
Apple Safari Full support · macOS & iOS
Full support
Microsoft Edge Full support · Chromium
Full support
Opera Full support · Modern versions
Full support
Internet Explorer Supported with workers in IE10+ (prefer modern browsers)
Legacy
Worker.postMessage() Excellent

Bottom line: Use postMessage to talk to workers; pack multiple values in arrays/objects, and transfer large buffers when you need zero-copy.

Conclusion

Worker.postMessage() is how the main thread sends data to a dedicated worker. Clone by default, transfer when you must move large buffers, and always pass an explicit message value.

Continue with terminate(), Worker(), or the JavaScript hub.

💡 Best Practices

✅ Do

  • Pack multiple fields in one object or array
  • Listen with onmessage before posting if you need the reply
  • Transfer large ArrayBuffers intentionally
  • Pass null explicitly for empty pings
  • Keep message shapes documented in your app

❌ Don’t

  • Expect functions or DOM nodes to clone
  • Use a transferred buffer after sending it
  • Call postMessage() with zero arguments
  • Assume shared references across threads
  • Forget error handlers on long-lived workers

Key Takeaways

Knowledge Unlocked

Five things to remember about postMessage()

The mailbox from main to worker.

5
Core concepts
📦02

One payload

array / object

Shape
🔁03

Clone

structured

Copy
04

Transfer

buffers move

Perf
🎯05

Baseline

since Jul 2015

Status

❓ Frequently Asked Questions

It sends a message from the main thread to a dedicated Worker. The data is delivered in the message event's data field inside the worker (via structured clone).
No. MDN marks Worker.postMessage() as Baseline Widely available (since July 2015). It is not Deprecated, Experimental, or Non-standard. It is available in Web Workers except Service Workers.
Almost any value the structured clone algorithm supports: strings, numbers, booleans, arrays, plain objects, Date, Map, Set, ArrayBuffer, and more—including objects with cyclical references. Functions and DOM nodes cannot be cloned.
postMessage sends one message payload. Put several values in an array or object, for example postMessage([a, b]) or postMessage({ a, b }).
An optional list of transferable objects (like ArrayBuffer) moves ownership to the worker. After transfer, the original buffer is neutered (often byteLength === 0) on the sending side.
No. It is mandatory. If you have nothing useful to send, pass null or undefined explicitly.
Did you know?

Structured clone can handle cyclical object graphs—something JSON.stringify cannot. That is why workers can receive richer data than a JSON round-trip would allow.

Next: terminate()

Immediately stop a dedicated worker from the main thread.

terminate() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

5 people found this page helpful