Home

workeronmessage

Worker.onmessage is a callback mechanism used to handle incoming messages in Web Workers. It can be set on a Worker instance in the main thread to receive messages from the worker, or in the worker’s global scope (self.onmessage) to receive messages from the main thread. For flexibility, it can also be attached with addEventListener('message', handler) to support multiple listeners or dynamic removal.

When a message arrives, the assigned handler is invoked with a MessageEvent argument. The payload is found

Usage examples:

In the main thread:

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

worker.onmessage = function(event) {

console.log('Main thread received:', event.data);

};

In the worker (worker.js):

self.onmessage = function(event) {

const input = event.data;

// perform work

self.postMessage(input); // send result back to main thread

};

Notes:

- onmessage is the conventional, straightforward way to handle a single handler; addEventListener offers more flexibility if

- Data is transferred using the structured clone algorithm; objects are cloned unless transferable objects are used.

in
event.data.
Depending
on
the
context,
the
event
may
also
expose
event.ports
(for
MessageChannel)
and
other
properties,
but
the
core
payload
is
event.data.
Messages
are
transferred
using
the
postMessage
method
on
the
opposite
side;
the
payload
can
be
a
primitive,
an
object,
or
a
transferable
object
such
as
an
ArrayBuffer
to
improve
efficiency.
multiple
listeners
or
dynamic
management
are
needed.