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 989057 of ServiceWorkerGlobalScope

  • Revision slug: Web/API/ServiceWorkerGlobalScope
  • Revision title: ServiceWorkerGlobalScope
  • Revision id: 989057
  • Created:
  • Creator: jpmedley
  • Is current revision? No
  • Comment Add a new specification.

Revision Content

{{SeeCompatTable}}{{APIRef("Service Workers API")}}

The ServiceWorkerGlobalScope interface of the ServiceWorker API represents the global execution context of a service worker.

Developers should keep in mind that the {{domxref("ServiceWorker.state")}} is not persisted across the termination/restart cycle, so each event handler should assume it's being invoked with a bare, default global state.

Once successfully registered, a service worker can and will be terminated when idle to conserve memory and processor power. An active service worker is automatically restarted to respond to events, such as {{domxref("ServiceWorkerGlobalScope.onfetch")}} or {{domxref("ServiceWorkerGlobalScope.onmessage")}}.

Additionally, synchronous requests are not allowed from within a service worker — only asynchronous requests, like those initiated via the {{domxref("GlobalFetch.fetch", "fetch()")}} method, can be used.

This interface inherits from the {{domxref("WorkerGlobalScope")}} interface, and its parent {{domxref("EventTarget")}}, and therefore implements properties from {{domxref("WindowTimers")}}, {{domxref("WindowBase64")}}, and {{domxref("WindowEventHandlers")}}.

{{InheritanceDiagram(700, 85, 20)}}

Properties

{{domxref("ServiceWorkerGlobalScope.clients")}} {{readonlyinline}}
Contains the {{domxref("Clients")}} object associated with the service worker.
{{domxref("ServiceWorkerGlobalScope.registration")}} {{readonlyinline}}
Contains the {{domxref("ServiceWorkerRegistration")}} object that represents the service worker's registration.
{{domxref("ServiceWorkerGlobalScope.caches")}} {{readonlyinline}}
Contains the {{domxref("CacheStorage")}} object associated with the service worker.

Event handlers

{{domxref("ServiceWorkerGlobalScope.onactivate")}}
An event handler fired whenever an {{Event("activate")}} event occurs — when a {{domxref("ServiceWorkerRegistration")}} acquires a new {{domxref("ServiceWorkerRegistration.active")}} worker.
{{domxref("ServiceWorkerGlobalScope.onfetch")}}
An event handler fired whenever a {{Event("fetch")}} event occurs — when a {{domxref("GlobalFetch.fetch", "fetch()")}} is called.
{{domxref("ServiceWorkerGlobalScope.oninstall")}}
An event handler fired whenever an {{Event("install")}} event occurs — when a {{domxref("ServiceWorkerRegistration")}} acquires a new {{domxref("ServiceWorkerRegistration.installing")}} worker.
{{domxref("ServiceWorkerGlobalScope.onmessage")}}
An event handler fired whenever a {{Event("message")}} event occurs — when incoming messages are received. Controlled pages can use the {{domxref("MessagePort.postMessage()")}} method to send messages to service workers. The service worker can optionally send a response back via the {{domxref("MessagePort")}} exposed in event.data.port, corresponding to the controlled page.
{{domxref("ServiceWorkerGlobalScope.onnotificationclick")}}
An event handler fired whenever a {{Event("notificationclick")}} event occurs — when a user clicks on a displayed notification.
{{domxref("ServiceWorkerGlobalScope.onpush")}}
An event handler fired whenever a {{Event("push")}} event occurs — when a server push notification is received.
{{domxref("ServiceWorkerGlobalScope.onpushsubscriptionchange")}}
An event handler fired whenever a {{Event("pushsubscriptionchange")}} event occurs — when a push subscription has been invalidated, or is about to be invalidated (e.g. when a push service sets an expiration time.)
{{domxref("ServiceWorkerGlobalScope.onsync")}}
An event handler fired whenever a {{Event("SyncEvent")}} event occurs. This is triggered when a call to {{domxref("SyncManager.register")}} is made from a service worker client page. The attempt to sync is made either immediately if the network is available or as soon as the network becomes available. 

Methods

{{domxref("ServiceWorkerGlobalScope.skipWaiting()")}}
Allows the current service worker registration to progress from waiting to active state while service worker clients are using it.

ServiceWorkerGlobalScope implements {{domxref("WorkerGlobalScope")}} — which implements {{domxref("GlobalFetch")}}. Therefore it also has the following property available to it:

{{domxref("GlobalFetch.fetch()")}}
Starts the process of fetching a resource. This returns a promise that resolves to the {{domxref("Response")}} object representing the response to your request. This algorithm is the entry point for the fetch handling handed to the service worker context.

Examples

This code snippet is from the service worker prefetch sample (see prefetch example live.) The {{domxref("ServiceWorkerGlobalScope.onfetch")}} event handler listens for the fetch event. When fired, the code returns a promise that resolves to the first matching request in the {{domxref("Cache")}} object. If no match is found, the code fetches a response from the network.

The code also handles exceptions thrown from the {{domxref("GlobalFetch.fetch", "fetch()")}} operation. Note that an HTTP error response (e.g., 404) will not trigger an exception. It will return a normal response object that has the appropriate error code set.

self.addEventListener('fetch', function(event) {
  console.log('Handling fetch event for', event.request.url);

  event.respondWith(
    caches.match(event.request).then(function(response) {
      if (response) {
        console.log('Found response in cache:', response);

        return response;
      }
      console.log('No response found in cache. About to fetch from network...');

      return fetch(event.request).then(function(response) {
        console.log('Response from network is:', response);

        return response;
      }).catch(function(error) {
        console.error('Fetching failed:', error);

        throw error;
      });
    })
  );
});

Specifications

Specification Status Comment
{{SpecName('Service Workers', '#service-worker-global-scope', 'ServiceWorkerGlobalScope')}} {{Spec2('Service Workers')}} Initial definition
{{SpecName('Fetch', '#concept-fetch', 'Fetch')}} {{Spec2('Fetch')}} Adds the {{domxref("ServiceWorkerGlobalScope.fetch", "fetch")}} method.
{{SpecName('Push API', '#widl-ServiceWorkerGlobalScope-onpush', 'onpush')}} {{Spec2('Push API')}} Adds the {{domxref("ServiceWorkerGlobalScope.onpush", "onpush")}} and {{domxref("ServiceWorkerGlobalScope.onpushsubscriptionchange", "onpushsubscriptionchange")}} event handlers.
{{SpecName('Web Notifications','#dom-serviceworkerglobalscope-onnotificationclick','onnotificationclick')}} {{Spec2('Web Notifications')}} Adds the {{domxref("ServiceWorkerGlobalScope.onnotificationclick", "onnotificationclick")}} event handler.
{{SpecName('Background Sync')}} {{Spec2('Background Sync')}} Adds the {{domxref("ServiceWorkerGlobalScope.onsync")}} event.

Browser compatibility

{{CompatibilityTable}}
Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support {{CompatChrome(40.0)}} {{CompatGeckoDesktop("44.0")}} {{CompatNo}} 24 {{CompatNo}}
onnotificationclick {{CompatVersionUnknown}} {{CompatGeckoDesktop("42.0")}} {{CompatNo}} {{CompatVersionUnknown}} {{CompatNo}}
Feature Android Firefox Mobile (Gecko) Firefox OS IE Mobile Opera Mobile Safari Mobile Chrome for Android
Basic support {{CompatUnknown}} {{CompatGeckoMobile("44.0")}} {{CompatVersionUnknown}} {{CompatNo}} {{CompatUnknown}} {{CompatNo}} {{CompatUnknown}}
onnotificationclick {{CompatUnknown}} {{CompatGeckoMobile("42.0")}} {{CompatVersionUnknown}} {{CompatNo}} {{CompatUnknown}} {{CompatNo}} {{CompatUnknown}}

See also

Revision Source

<div>{{SeeCompatTable}}{{APIRef("Service Workers API")}}</div>

<p>The <code>ServiceWorkerGlobalScope</code> interface of the <a href="/en-US/docs/Web/API/ServiceWorker_API">ServiceWorker API</a> represents the global execution context of a service worker.</p>

<p>Developers should keep in mind that the {{domxref("ServiceWorker.state")}} is not persisted across the termination/restart cycle, so each event handler should assume it's being invoked with a bare, default global state.</p>

<p>Once successfully registered, a service worker can and will be terminated when idle to conserve memory and processor power. An active service worker is automatically restarted to respond to events, such as {{domxref("ServiceWorkerGlobalScope.onfetch")}} or {{domxref("ServiceWorkerGlobalScope.onmessage")}}.</p>

<p>Additionally, synchronous requests are not allowed from within a service worker — only asynchronous requests, like those initiated via the {{domxref("GlobalFetch.fetch", "fetch()")}} method, can be used.</p>

<p>This interface inherits from the {{domxref("WorkerGlobalScope")}} interface, and its parent {{domxref("EventTarget")}}, and therefore implements properties from {{domxref("WindowTimers")}}, {{domxref("WindowBase64")}}, and {{domxref("WindowEventHandlers")}}.</p>

<p>{{InheritanceDiagram(700, 85, 20)}}</p>

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

<dl>
 <dt>{{domxref("ServiceWorkerGlobalScope.clients")}} {{readonlyinline}}</dt>
 <dd>Contains the {{domxref("Clients")}} object associated with the service worker.</dd>
 <dt>{{domxref("ServiceWorkerGlobalScope.registration")}} {{readonlyinline}}</dt>
 <dd>Contains the {{domxref("ServiceWorkerRegistration")}} object that represents the service worker's registration.</dd>
 <dt>{{domxref("ServiceWorkerGlobalScope.caches")}} {{readonlyinline}}</dt>
 <dd>Contains the {{domxref("CacheStorage")}} object associated with the service worker.</dd>
</dl>

<h3 id="Event_handlers">Event handlers</h3>

<dl>
 <dt>{{domxref("ServiceWorkerGlobalScope.onactivate")}}</dt>
 <dd>An event handler fired whenever an {{Event("activate")}} event occurs — when a {{domxref("ServiceWorkerRegistration")}} acquires a new {{domxref("ServiceWorkerRegistration.active")}} worker.</dd>
 <dt>{{domxref("ServiceWorkerGlobalScope.onfetch")}}</dt>
 <dd>An event handler fired whenever a {{Event("fetch")}} event occurs — when a {{domxref("GlobalFetch.fetch", "fetch()")}} is called.</dd>
 <dt>{{domxref("ServiceWorkerGlobalScope.oninstall")}}</dt>
 <dd>An event handler fired whenever an {{Event("install")}} event occurs — when a {{domxref("ServiceWorkerRegistration")}} acquires a new {{domxref("ServiceWorkerRegistration.installing")}} worker.</dd>
 <dt>{{domxref("ServiceWorkerGlobalScope.onmessage")}}</dt>
 <dd>An event handler fired whenever a {{Event("message")}} event occurs — when incoming messages are received. Controlled pages can use the {{domxref("MessagePort.postMessage()")}} method to send messages to service workers. The service worker can optionally send a response back via the {{domxref("MessagePort")}} exposed in <a href="https://html.spec.whatwg.org/multipage/comms.html#messageport"><code>event.data.port</code></a>, corresponding to the controlled page.</dd>
 <dt>{{domxref("ServiceWorkerGlobalScope.onnotificationclick")}}</dt>
 <dd>An event handler fired whenever a {{Event("notificationclick")}} event occurs — when a user clicks on a displayed notification.</dd>
 <dt>{{domxref("ServiceWorkerGlobalScope.onpush")}}</dt>
 <dd>An event handler fired whenever a {{Event("push")}} event occurs — when a server push notification is received.</dd>
 <dt>{{domxref("ServiceWorkerGlobalScope.onpushsubscriptionchange")}}</dt>
 <dd>An event handler fired whenever a {{Event("pushsubscriptionchange")}} event occurs — when a push subscription has been invalidated, or is about to be invalidated (e.g. when a push service sets an expiration time.)</dd>
 <dt>{{domxref("ServiceWorkerGlobalScope.onsync")}}</dt>
 <dd>An event handler fired whenever a {{Event("SyncEvent")}} event occurs. This is triggered when a call to {{domxref("SyncManager.register")}} is made from a service worker client page. The attempt to sync is made either&nbsp;immediately if the network is available or as soon as the network becomes available.&nbsp;</dd>
</dl>

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

<dl>
 <dt>{{domxref("ServiceWorkerGlobalScope.skipWaiting()")}}</dt>
 <dd>Allows the current service worker registration to progress from waiting to active state while service worker clients are using it.</dd>
</dl>

<p><code>ServiceWorkerGlobalScope</code> implements {{domxref("WorkerGlobalScope")}} — which implements {{domxref("GlobalFetch")}}. Therefore it also has the following property available to it:</p>

<dl>
 <dt>{{domxref("GlobalFetch.fetch()")}}</dt>
 <dd>Starts the process of fetching a resource. This returns a promise that resolves to the {{domxref("Response")}} object representing the response to your request. This algorithm is the entry point for the fetch handling handed to the service worker context.</dd>
</dl>

<h2 id="Examples">Examples</h2>

<p>This code snippet is from the <a href="https://github.com/GoogleChrome/samples/blob/gh-pages/service-worker/prefetch/service-worker.js">service worker prefetch sample</a> (see <a href="https://googlechrome.github.io/samples/service-worker/prefetch/">prefetch example live</a>.) The {{domxref("ServiceWorkerGlobalScope.onfetch")}} event handler listens for the <code>fetch</code> event. When fired, the code returns a promise that resolves to the first matching request in the {{domxref("Cache")}} object. If no match is found, the code fetches a response from the network.</p>

<p>The code also handles exceptions thrown from the {{domxref("GlobalFetch.fetch", "fetch()")}} operation. Note that an HTTP error response (e.g., 404) will not trigger an exception. It will return a normal response object that has the appropriate error code set.</p>

<pre class="brush: js">
self.addEventListener('fetch', function(event) {
  console.log('Handling fetch event for', event.request.url);

  event.respondWith(
    caches.match(event.request).then(function(response) {
      if (response) {
        console.log('Found response in cache:', response);

        return response;
      }
      console.log('No response found in cache. About to fetch from network...');

      return fetch(event.request).then(function(response) {
        console.log('Response from network is:', response);

        return response;
      }).catch(function(error) {
        console.error('Fetching failed:', error);

        throw error;
      });
    })
  );
});</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('Service Workers', '#service-worker-global-scope', 'ServiceWorkerGlobalScope')}}</td>
   <td>{{Spec2('Service Workers')}}</td>
   <td>Initial definition</td>
  </tr>
  <tr>
   <td>{{SpecName('Fetch', '#concept-fetch', 'Fetch')}}</td>
   <td>{{Spec2('Fetch')}}</td>
   <td>Adds the {{domxref("ServiceWorkerGlobalScope.fetch", "fetch")}} method.</td>
  </tr>
  <tr>
   <td>{{SpecName('Push API', '#widl-ServiceWorkerGlobalScope-onpush', 'onpush')}}</td>
   <td>{{Spec2('Push API')}}</td>
   <td>Adds the {{domxref("ServiceWorkerGlobalScope.onpush", "onpush")}} and {{domxref("ServiceWorkerGlobalScope.onpushsubscriptionchange", "onpushsubscriptionchange")}} event handlers.</td>
  </tr>
  <tr>
   <td>{{SpecName('Web Notifications','#dom-serviceworkerglobalscope-onnotificationclick','onnotificationclick')}}</td>
   <td>{{Spec2('Web Notifications')}}</td>
   <td>Adds the {{domxref("ServiceWorkerGlobalScope.onnotificationclick", "onnotificationclick")}} event handler.</td>
  </tr>
  <tr>
   <td>{{SpecName('Background Sync')}}</td>
   <td>{{Spec2('Background Sync')}}</td>
   <td>Adds the&nbsp;{{domxref("ServiceWorkerGlobalScope.onsync")}} event.</td>
  </tr>
 </tbody>
</table>

<h2 id="Browser_compatibility">Browser compatibility</h2>

<div>{{CompatibilityTable}}</div>

<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 (WebKit)</th>
  </tr>
  <tr>
   <td>Basic support</td>
   <td>{{CompatChrome(40.0)}}</td>
   <td>{{CompatGeckoDesktop("44.0")}}</td>
   <td>{{CompatNo}}</td>
   <td>24</td>
   <td>{{CompatNo}}</td>
  </tr>
  <tr>
   <td><code>onnotificationclick</code></td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatGeckoDesktop("42.0")}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatNo}}</td>
  </tr>
 </tbody>
</table>
</div>

<div id="compat-mobile">
<table class="compat-table">
 <tbody>
  <tr>
   <th>Feature</th>
   <th>Android</th>
   <th>Firefox Mobile (Gecko)</th>
   <th>Firefox OS</th>
   <th>IE Mobile</th>
   <th>Opera Mobile</th>
   <th>Safari Mobile</th>
   <th>Chrome for Android</th>
  </tr>
  <tr>
   <td>Basic support</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatGeckoMobile("44.0")}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatUnknown}}</td>
  </tr>
  <tr>
   <td><code>onnotificationclick</code></td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatGeckoMobile("42.0")}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatUnknown}}</td>
  </tr>
 </tbody>
</table>
</div>

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

<ul>
 <li><a href="/en-US/docs/Web/API/ServiceWorker_API/Using_Service_Workers">Using Service Workers</a></li>
 <li><a class="external external-icon" href="https://github.com/mdn/sw-test">Service workers basic code example</a></li>
 <li><a class="external external-icon" href="https://jakearchibald.github.io/isserviceworkerready/">Is ServiceWorker ready?</a></li>
 <li>{{jsxref("Promise")}}</li>
 <li><a href="/en-US/docs/Web/Guide/Performance/Using_web_workers">Using web workers</a></li>
</ul>
Revert to this revision