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.jsconst 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.jsaddEventListener('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 ...

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.