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.

Syntax

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

js

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

onmessage = (event) => {};

Event type

Event properties

This interface also inherits properties from its parent, Event.

MessageEvent.data 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).

Example

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.

js

// 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: ${e.data[0] * e.data[1]}`;
  console.log("Posting message back to main script");
  postMessage(workerResult);
};

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

js

// main.js

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

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

js

// worker.js

self.addEventListener("message", (e) => {
  result.textContent = e.data;
  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).

Specifications

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

Browser compatibility

BCD tables only load in the browser

See also