SharedWorker()

The SharedWorker() constructor creates a SharedWorker object that executes the script at the specified URL. This script must obey the same-origin policy.

If the URL has an invalid syntax or if the same-origin policy is violated, a DOMException of type SECURITY_ERR is thrown.

Note: there is disagreement among browser manufacturers about whether a data URI is of the same origin or not. Although Gecko 10.0 (Firefox 10.0 / Thunderbird 10.0 / SeaMonkey 2.7) and later accept data URIs, that's not the case in all other browsers.

Syntax

JavaScript
var myWorker = new SharedWorker("aURL", name);

Arguments

aURL
A DOMString representing the URL of the script the worker will execute. It must obey the same-origin policy.
name
An optional argument that specifies an existing SharedWorkerGlobalScope.name — if this is specified then that SharedWorkerGlobalScope will be used as the scope for this shared worker.

Example

The following code snippet shows creation of a SharedWorker object using the SharedWorker() constructor and subsequent usage of the object:

JavaScript
var myWorker = new SharedWorker("worker.js");

myWorker.port.start();

first.onchange = function() {
  myWorker.port.postMessage([first.value,second.value]);
  console.log('Message posted to worker');
}

second.onchange = function() {
  myWorker.port.postMessage([first.value,second.value]);
  console.log('Message posted to worker');
}

myWorker.port.onmessage = function(e) {
  result1.textContent = e.data;
  console.log('Message received from worker');
}

For a full example, see our Basic shared worker example (run shared worker.)

Specifications

Specification Status Comment
WHATWG HTML Living Standard
The definition of 'SharedWorker()' in that specification.
Living Standard No change from Web Workers.
Web Workers
The definition of 'SharedWorker()' in that specification.
Candidate Recommendation Initial definition

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Support 4 29.0 (29.0) Not supported 10.60 5
Not supported 6.1
Feature Android Chrome for Android Firefox Mobile (Gecko) Firefox OS (Gecko) IE Mobile Opera Mobile Safari Mobile
Support Not supported Not supported 33.0 (33.0) 2.1 Not supported 11.5 5.1
Not supported 7.1

See also

License

© 2016 Mozilla Contributors
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-us/docs/web/api/sharedworker/sharedworker

API Constructor Reference Shared Workers SharedWorker Web Workers