Listening for messages on the worker script

Workers themselves have access to the self object, to which you can attach similar event listeners, as previously discussed. Let us see how that goes:

// myworker.jsself.addEventListener('message', e => {    console.log(e.data); // data sent by main script});

Here, the message event listener is fired whenever the main script sends a message to this particular web worker. We simply console-log what the main script sent with console.log(e.data).

You can omit the self keyword here if you wish. By default, in workers, events will be attached to self.

Get Learn ECMAScript - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.