The action triggered by this event is defined in a function set as the event handler for the relevant message event (e.g. using an onmessage handler as listed above).
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).
Instance methods
This interface also inherits methods from its parent, Event.
Initializes a message event. Do not use this anymore — use the MessageEvent() constructor instead.
Examples
In our Basic shared worker example (run shared worker), we have two HTML pages, each of which uses some JavaScript to perform a simple 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:
js
const myWorker =newSharedWorker("worker.js");
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:
js
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:
js
first.onchange=()=>{
myWorker.port.postMessage([first.value, second.value]);
console.log("Message posted to worker");};
second.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 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 MessagePortstart() method to start the port, and the onmessage handler to deal with messages sent from the main threads.
js
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.};