Get to know MDN better
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
Note: This feature is available in Web Workers.
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.
Event MessageEventCreates a new MessageEvent.
This interface also inherits properties from its parent, Event.
MessageEvent.data Read onlyThe data sent by the message emitter.
MessageEvent.origin Read onlyA string representing the origin of the message emitter.
MessageEvent.lastEventId Read onlyA string representing a unique ID for the event.
MessageEvent.source Read onlyA MessageEventSource (which can be a WindowProxy, MessagePort, or ServiceWorker object) representing the message emitter.
MessageEvent.ports Read onlyAn array of MessagePort objects containing all MessagePort objects sent with the message, in order.
This interface also inherits methods from its parent, Event.
initMessageEvent()Initializes a message event. Do not use this anymore — use the MessageEvent() constructor instead.
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 SharedWorker object using the SharedWorker() constructor. Both scripts contain this:
Both scripts then access the worker through a MessagePort object created using the SharedWorker.port property. If the onmessage event is attached using addEventListener, the port is manually started using its start() method:
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:
Inside the worker we use the onconnect handler to connect to the same port discussed above. The ports associated with that worker are accessible in the connect event's ports property — we then use MessagePort start() method to start the port, and the onmessage handler to deal with messages sent from the main threads.
| HTML # the-messageevent-interface |
Enable JavaScript to view this browser compatibility table.
This page was last modified on Dec 31, 2024 by MDN contributors.
Your blueprint for a better internet.
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998–2026 by individual mozilla.org contributors. Content available under a Creative Commons license.