Listening for messages on the main script

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 ...

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.