Listening for messages on the worker script

Similarly, self is defined here; however, window is not. So, you can use  self.addEventListener or addEventListener (or just onconnect = function()):

// myworker.jsaddEventListener('connect', e => {    console.log(e.ports);    const port = e.ports[0];    port.start();    port.addEventListener('message', event => {        console.log('Some calling script says.. ', event.data);    });});

Here, the event contains the details about the ports our script is connected to. We pick up the connecting port and establish a connection with it.

Similar to our main script, we have to specify port.start() here for a successful communication between the two files.

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.