The SharedWorker()
constructor creates a SharedWorker
object that executes the script at the specified URL. This script must obey the same-origin policy.
Note: there is disagreement among browser manufacturers about whether a data URL is of the same origin or not. Although Firefox 10.0 and later accept data URLs, that's not the case in all other browsers.
new SharedWorker(aURL)
new SharedWorker(aURL, name)
new SharedWorker(aURL, options)
The following code snippet shows creation of a SharedWorker
object using the SharedWorker()
constructor and subsequent usage of the object:
const myWorker = new SharedWorker("worker.js");
myWorker.port.start();
first.onchange = () => {
myWorker.port.postMessage([first.value, second.value]);
console.log("Message posted to worker");
};
second.onchange = () => {
myWorker.port.postMessage([first.value, second.value]);
console.log("Message posted to worker");
};
myWorker.port.onmessage = (e) => {
result1.textContent = e.data;
console.log("Message received from worker");
};
For a full example, see our Basic shared worker example (run shared worker.)