files/en-us/web/api/messageevent/index.md
{{APIRef("HTML DOM")}}{{AvailableInWorkers}}
The MessageEvent interface represents a message received by a target object.
This is used to represent messages in:
The action triggered by this event is defined in a function set as the event handler for the relevant message event.
{{InheritanceDiagram}}
MessageEvent.This interface also inherits properties from its parent, {{domxref("Event")}}.
MessageEventSource (which can be a {{glossary("WindowProxy")}}, {{domxref("MessagePort")}}, or {{domxref("ServiceWorker")}} object) representing the message emitter.This interface also inherits methods from its parent, {{domxref("Event")}}.
In our Basic shared worker example (run shared worker), we have two HTML pages, each of which uses some JavaScript to perform a calculation. The different scripts are using the same worker file to perform the calculation — they can both access it, even if their pages are running inside different windows.
The following code snippet shows creation of a {{domxref("SharedWorker")}} object using the {{domxref("SharedWorker.SharedWorker", "SharedWorker()")}} constructor. Both scripts contain this:
const myWorker = new SharedWorker("worker.js");
Both scripts then access the worker through a {{domxref("MessagePort")}} object created using the {{domxref("SharedWorker.port")}} property. If the onmessage event is attached using addEventListener, the port is manually started using its start() method:
myWorker.port.start();
When the port is started, both scripts post messages to the worker and handle messages sent from it using port.postMessage() and port.onmessage, respectively:
[first, second].forEach((input) => {
input.onchange = () => {
myWorker.port.postMessage([first.value, second.value]);
console.log("Message posted to worker");
};
});
myWorker.port.onmessage = (e) => {
result1.textContent = e.data;
console.log("Message received from worker");
};
Inside the worker we use the {{domxref("SharedWorkerGlobalScope.connect_event", "onconnect")}} handler to connect to the same port discussed above. The ports associated with that worker are accessible in the {{domxref("SharedWorkerGlobalScope/connect_event", "connect")}} event's ports property — we then use {{domxref("MessagePort")}} start() method to start the port, and the onmessage handler to deal with messages sent from the main threads.
onconnect = (e) => {
const port = e.ports[0];
port.addEventListener("message", (e) => {
const workerResult = `Result: ${e.data[0] * e.data[1]}`;
port.postMessage(workerResult);
});
port.start(); // Required when using addEventListener. Otherwise called implicitly by onmessage setter.
};
{{Specifications}}
{{Compat}}