Home

MessageEvent

MessageEvent is a DOM event that represents a message sent between browsing contexts or between a context and a worker using the postMessage API. It is delivered to the target that receives the message, such as a window, an embedded frame, a Web Worker, or a Service Worker. The event object exposed to handlers is a MessageEvent and inherits from Event.

The primary properties of a MessageEvent include data, origin, lastEventId, source, and ports. The data property

Usage typically involves calling postMessage on a target (window.postMessage or port.postMessage) with an optional transfer parameter

Security considerations emphasize validating the origin and, when possible, restricting which sources may send messages. MessageEvent

holds
the
message
payload,
which
can
be
any
value
that
can
be
cloned
with
the
structured
clone
algorithm.
The
origin
string
indicates
the
origin
of
the
message
sender,
enabling
checks
for
cross-origin
messaging.
The
lastEventId
property
is
a
string
representing
the
last
event
identifier
for
certain
channel
messaging
scenarios.
The
source
property
provides
a
reference
to
the
sender
context,
such
as
a
window
or
a
MessagePort.
The
ports
array
contains
any
MessagePort
objects
that
were
transferred
with
the
message,
allowing
the
receiver
to
establish
a
two-way
channel.
to
include
ports.
On
the
receiving
side,
code
subscribes
to
the
message
event
with
addEventListener('message',
handler)
or
an
onmessage
handler.
The
handler
can
access
event.data,
verify
event.origin
if
needed,
and
respond
via
event.source
or
the
ports
in
event.ports.
is
a
standard
part
of
the
Web
Messaging
API
and
is
widely
supported
in
modern
browsers,
with
behavior
tailored
to
the
specific
messaging
context.