DedicatedWorkerGlobalScope: message event

The message event is fired on a DedicatedWorkerGlobalScope object when the worker receives a message from its parent (i.e. when the parent sends a message using Worker.postMessage()).

This event is not cancellable and does not bubble.


Use the event name in methods like addEventListener(), or set an event handler property.

addEventListener("message", (event) => {});

onmessage = (event) => {};

Event type

Event properties

This interface also inherits properties from its parent, Event. Read only

The data sent by the message emitter.

MessageEvent.origin Read only

A string representing the origin of the message emitter.

MessageEvent.lastEventId Read only

A string representing a unique ID for the event.

MessageEvent.source Read only

A MessageEventSource (which can be a Window, MessagePort, or ServiceWorker object) representing the message emitter.

MessageEvent.ports Read only

An array of MessagePort objects representing the ports associated with the channel the message is being sent through (where appropriate, e.g. in channel messaging or when sending a message to a shared worker).


The following code snippet shows creation of a Worker object using the Worker() constructor. Messages are passed to the worker when the value inside the form input first changes. An onmessage handler is also present, to deal with messages are passed back from the worker.

// main.js

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

first.onchange = () => {
  myWorker.postMessage([first.value, second.value]);
  console.log("Message posted to worker");

// worker.js

self.onmessage = (e) => {
  console.log("Message received from main script");
  const workerResult = `Result: ${[0] *[1]}`;
  console.log("Posting message back to main script");

In the main.js script, an onmessage handler is used to handle messages from the worker script:

// main.js

myWorker.onmessage = (e) => {
  result.textContent =;
  console.log("Message received from worker");

Alternatively, the script can listen for the message using addEventListener():

// worker.js

self.addEventListener("message", (e) => {
  result.textContent =;
  console.log("Message received from worker");

Notice how in the main script, onmessage has to be called on myWorker, whereas inside the worker script you just need onmessage because the worker is effectively the global scope (DedicatedWorkerGlobalScope).

For a full example, see our Basic dedicated worker example (run dedicated worker).


HTML Standard
# event-message
HTML Standard
# handler-dedicatedworkerglobalscope-onmessage

Browser compatibility

BCD tables only load in the browser

See also