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.js
addEventListener('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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.21.247.9