Here, unlike with dedicated workers, we have to add the onmessage event on the port property which is available on the shared worker object:
// script.jsconst awesomeworker = new SharedWorker('myworker.js');awesomeworker.port.start(); // importantawesomeworker.port.addEventListener('message', e => { // notice the .port console.log('Shared worker says .. ', e.data);});
This event is triggered whenever our SharedWorker replies to this particular script.
Notice the line awesomeworker.port.start();, which instructs the shared worker to interact with this script. When using addEventListener, it is mandatory to start the communication with the port.start() line from both files (worker and script) for two-way ...