Home

onmessage

Onmessage is an event handler property used in JavaScript to handle messages delivered by the postMessage API. It is available on various objects that can receive messages, such as Window, Worker, DedicatedWorkerGlobalScope, SharedWorker, MessagePort, and WebSocket. Assigning a function to onmessage designates a single handler for incoming message events on that object.

When a message arrives, the assigned onmessage function is invoked with a MessageEvent object. The event typically

Common usage includes communication with web workers and cross-document messaging. For a worker, the pattern is:

Onmessage differs from addEventListener in that it supports only a single handler assignment per target. Replacing

exposes
a
data
property
containing
the
message
payload,
and,
depending
on
the
source,
additional
properties
such
as
origin
(for
cross-origin
window
messages),
source
(the
sender),
and
ports
(for
channel-based
communication).
The
exact
shape
of
the
event
can
vary
by
context
(for
example,
worker
messages
versus
window
messages).
create
a
worker,
assign
a
handler
to
worker.onmessage,
and
send
messages
with
postMessage.
In
the
worker
context,
onmessage
receives
the
event
from
the
main
thread,
and
the
worker
can
respond
with
postMessage.
In
window
contexts,
onmessage
handles
messages
sent
via
postMessage
from
other
windows
or
iframes,
with
access
to
event.origin
and
event.source.
it
replaces
the
previous
handler,
whereas
addEventListener
lets
you
attach
multiple
listeners.
To
remove,
set
the
property
to
null.
It
is
widely
supported
in
modern
browsers
and
also
used
in
WebSocket
communication.