Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Revision 732801 of SharedWorker

  • Revision slug: Web/API/SharedWorker
  • Revision title: SharedWorker
  • Revision id: 732801
  • Created:
  • Creator: Jeremie
  • Is current revision? No
  • Comment

Revision Content

{{APIRef}}

The SharedWorker interface represents a specific kind of worker that can be accessed from several browsing contexts, such as several windows, iframes or even workers. They implement an interface different than dedicated workers and have a different global scope, {{domxref("SharedWorkerGlobalScope")}}.

Note: If SharedWorker can be access from several browsing contexts, all those browsing contexts must share the exact same origin (same protocol, host and port).

Properties

Inherits properties from its parent, {{domxref("EventTarget")}}, and implements properties from {{domxref("AbstractWorker")}}.

{{domxref("AbstractWorker.onerror")}}
Is an {{ domxref("EventListener") }} that is called whenever an {{domxref("ErrorEvent")}} of type error bubbles through the worker.
{{domxref("SharedWorker.port")}} {{readonlyInline}}
Returns a {{domxref("MessagePort")}} object used to communicate and control the shared worker.

Constructors

{{domxref("SharedWorker.SharedWorker", "SharedWorker()")}}
Creates a shared web worker that executes the script at the specified URL.

Methods

Inherits methods from its parent, {{domxref("EventTarget")}}, and implements properties from {{domxref("AbstractWorker")}}.

Example

In our Basic shared worker example (run shared worker), we have two HTML pages, each of which uses some JavaScript to perform a simple calculation. The different scripts are using the same worker file to perform the calculation — they can both access it, even if their pages are running inside different windows.

The following code snippet shows creation of a SharedWorker object using the {{domxref("SharedWorker.SharedWorker", "SharedWorker()")}} constructor. Both scripts contain this:

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

Both scripts then access the worker through a {{domxref("MessagePort")}} obect created using the {{domxref("SharedWorker.port")}} property — the port is started using its start() method:

myWorker.port.start();

When the port is started, both scripts post messages to the worker and handle messages sent from it using port.postMessage() and port.onmessage, respectively:

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');
  }

Inside the worker we use the {{domxref("SharedWorkerGlobalScope.onconnect")}} handler to connect to the same port discussed above. The ports associated with that worker are accessible in the {{event("connect")}} event's ports property — we then use {{domxref("MessagePort")}} start() method to start the port, and the onmessage handler to deal with messages sent from the main threads.

onconnect = function(e) {
    var port = e.ports[0];

    port.onmessage = function(e) {
      var workerResult = 'Result: ' + (e.data[0] * e.data[1]);
      port.postMessage(workerResult);
    }

    port.start();
}

Specifications

Specification Status Comment
{{SpecName('HTML WHATWG', "#sharedworker", "SharedWorker")}} {{Spec2('HTML WHATWG')}} No change from {{SpecName("Web Workers")}}.
{{SpecName('Web Workers', "#sharedworker", "SharedWorker")}} {{Spec2('Web Workers')}} Initial definition.

Browser compatibility

{{ CompatibilityTable() }}

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Support {{CompatChrome(4)}} {{CompatGeckoDesktop(29.0)}} {{CompatNo}} {{CompatOpera(10.60)}} 5, but unsupported as of 6.1
Feature Android Chrome for Android Firefox Mobile (Gecko) Firefox OS (Gecko) IE Mobile Opera Mobile Safari Mobile
Support {{CompatNo}} {{ CompatNo() }} {{CompatGeckoMobile("33.0")}} 2.1 {{CompatNo}} 11.5 5.1, but unsupported as of 7.1

See also

Revision Source

<p>{{APIRef}}</p>

<p>The <code><strong>SharedWorker</strong></code> interface represents a specific kind of worker that can be <em>accessed</em> from several browsing contexts, such as several windows, iframes or even workers. They implement an interface different than dedicated workers and have a different global scope, {{domxref("SharedWorkerGlobalScope")}}.</p>

<div class="note">
<p><strong>Note:</strong> If SharedWorker can be access from several browsing contexts, all those browsing contexts must share the exact same origin (same protocol, host and port).</p>
</div>

<h2 id="Properties">Properties</h2>

<p><em>Inherits properties from its parent, {{domxref("EventTarget")}}, and implements properties from {{domxref("AbstractWorker")}}.</em></p>

<dl>
 <dt>{{domxref("AbstractWorker.onerror")}}</dt>
 <dd>Is an {{ domxref("EventListener") }} that is called whenever an {{domxref("ErrorEvent")}} of type <code>error</code> bubbles through the worker.</dd>
 <dt>{{domxref("SharedWorker.port")}} {{readonlyInline}}</dt>
 <dd>Returns a {{domxref("MessagePort")}} object used to communicate and control the shared worker.</dd>
</dl>

<h2 id="Constructors">Constructors</h2>

<dl>
 <dt>{{domxref("SharedWorker.SharedWorker", "SharedWorker()")}}</dt>
 <dd>Creates a shared web worker that executes the script at the specified URL.</dd>
</dl>

<h2 id="Methods">Methods</h2>

<p><em>Inherits methods from its parent, {{domxref("EventTarget")}}, and implements properties from {{domxref("AbstractWorker")}}.</em></p>

<h2 id="Example">Example</h2>

<p>In our <a class="external external-icon" href="https://github.com/mdn/simple-shared-worker">Basic shared worker example</a> (<a class="external external-icon" href="https://mdn.github.io/simple-shared-worker/">run shared worker</a>), we have two HTML pages, each of which uses some JavaScript to perform a simple calculation. The different scripts are using the same worker file to perform the calculation — they can both access it, even if their pages are running inside different windows.</p>

<p>The following code snippet shows creation of a <code>SharedWorker</code> object using the {{domxref("SharedWorker.SharedWorker", "SharedWorker()")}} constructor. Both scripts contain this:</p>

<pre class="brush: js">
var myWorker = new SharedWorker("worker.js");
</pre>

<p>Both scripts then access the worker through a {{domxref("MessagePort")}} obect created using the {{domxref("SharedWorker.port")}} property — the port is started using its <code>start()</code> method:</p>

<pre class="brush: js">
myWorker.port.start();</pre>

<p>When the port is started, both scripts post messages to the worker and handle messages sent from it using <code>port.postMessage()</code> and <code>port.onmessage</code>, respectively:</p>

<pre class="brush: js">
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');
  }</pre>

<p>Inside the worker we use the {{domxref("SharedWorkerGlobalScope.onconnect")}} handler to connect to the same port discussed above. The ports associated with that worker are accessible in the {{event("connect")}} event's <code>ports</code> property — we then use {{domxref("MessagePort")}} <code>start()</code> method to start the port, and the <code>onmessage</code> handler to deal with messages sent from the main threads.</p>

<pre class="brush: js">
onconnect = function(e) {
    var port = e.ports[0];

    port.onmessage = function(e) {
      var workerResult = 'Result: ' + (e.data[0] * e.data[1]);
      port.postMessage(workerResult);
    }

    port.start();
}</pre>

<h2 id="Specifications">Specifications</h2>

<table class="standard-table">
 <tbody>
  <tr>
   <th scope="col">Specification</th>
   <th scope="col">Status</th>
   <th scope="col">Comment</th>
  </tr>
  <tr>
   <td>{{SpecName('HTML WHATWG', "#sharedworker", "SharedWorker")}}</td>
   <td>{{Spec2('HTML WHATWG')}}</td>
   <td>No change from {{SpecName("Web Workers")}}.</td>
  </tr>
  <tr>
   <td>{{SpecName('Web Workers', "#sharedworker", "SharedWorker")}}</td>
   <td>{{Spec2('Web Workers')}}</td>
   <td>Initial definition.</td>
  </tr>
 </tbody>
</table>

<h2 id="Browser_Compatibility" name="Browser_Compatibility">Browser compatibility</h2>

<p>{{ CompatibilityTable() }}</p>

<div id="compat-desktop">
<table class="compat-table">
 <tbody>
  <tr>
   <th>Feature</th>
   <th>Chrome</th>
   <th>Firefox (Gecko)</th>
   <th>Internet Explorer</th>
   <th>Opera</th>
   <th>Safari</th>
  </tr>
  <tr>
   <td>Support</td>
   <td>{{CompatChrome(4)}}</td>
   <td>{{CompatGeckoDesktop(29.0)}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatOpera(10.60)}}</td>
   <td>5, but unsupported as of 6.1</td>
  </tr>
 </tbody>
</table>
</div>

<div id="compat-mobile">
<table class="compat-table">
 <tbody>
  <tr>
   <th>Feature</th>
   <th>Android</th>
   <th>Chrome for Android</th>
   <th>Firefox Mobile (Gecko)</th>
   <th>Firefox OS (Gecko)</th>
   <th>IE Mobile</th>
   <th>Opera Mobile</th>
   <th>Safari Mobile</th>
  </tr>
  <tr>
   <td>Support</td>
   <td>{{CompatNo}}</td>
   <td>{{ CompatNo() }}</td>
   <td>{{CompatGeckoMobile("33.0")}}</td>
   <td>2.1</td>
   <td>{{CompatNo}}</td>
   <td>11.5</td>
   <td>5.1, but unsupported as of 7.1</td>
  </tr>
 </tbody>
</table>
</div>

<h2 id="See_also">See also</h2>

<ul>
 <li>{{ domxref("Worker") }}</li>
 <li><a class="internal" href="/en-US/docs/Web/Guide/Performance/Using_web_workers">Using web workers</a></li>
</ul>
Revert to this revision