Sending messages from the worker script

If you've recognized the difference between how we call methods in dedicated workers versus how we call them in shared workers, well done! Instead of just calling methods on self, we're calling all the dedicated web worker methods on the port object, which is how the worker distinguishes between so many scripts that (can possibly) talk to it:

// 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);
// some work
port.postMessage("Hello ;)");
});
});

It is exactly like the code above, but with the exception that this time our shared worker replies to whoever sent the message and says Hello to it.

If you have two instances of the HTML page which loads script.js (that is, the new SharedWorker) running, both have separate port connections with the shared worker.
..................Content has been hidden....................

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