Terminating a shared worker completely

A shared worker can itself be permanently terminated by calling self.close() inside its JS. You can also send a message from the parent script to kill the worker:

// script.js

const awesomeworker = new SharedWorker('myworker.js');
awesomeworker.port.start();

awesomeworker.port.postMessage({type: 'cmd', action: 'die'});

We simply sent a message from our main script to our shared worker and passed the message that the shared worker should be terminated permanently.

The worker file looks like:

// myworker.js

addEventListener('connect', e => {
const port = e.ports[0];
port.start();
port.addEventListener('message', event => {
if(event.data.type == 'cmd' && event.data.action == 'die') {
self.close(); // terminates worker
}
});
});

After verifying that the main script really wants to terminate the worker for all instances, the worker calls the close method on itself, which terminates it.

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

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