workeronmessage
Worker.onmessage is a callback mechanism used to handle incoming messages in Web Workers. It can be set on a Worker instance in the main thread to receive messages from the worker, or in the worker’s global scope (self.onmessage) to receive messages from the main thread. For flexibility, it can also be attached with addEventListener('message', handler) to support multiple listeners or dynamic removal.
When a message arrives, the assigned handler is invoked with a MessageEvent argument. The payload is found
const worker = new Worker('worker.js');
worker.onmessage = function(event) {
console.log('Main thread received:', event.data);
};
self.onmessage = function(event) {
self.postMessage(input); // send result back to main thread
};
- onmessage is the conventional, straightforward way to handle a single handler; addEventListener offers more flexibility if
- Data is transferred using the structured clone algorithm; objects are cloned unless transferable objects are used.