--- title: ServiceWorkerGlobalScope slug: Web/API/ServiceWorkerGlobalScope translation_of: Web/API/ServiceWorkerGlobalScope ---
{{APIRef("Service Workers API")}}

ServiceWorker API 的ServiceWorkerGlobalScope 接口,代表一个service worker的全局执行上下文。

开发者应该知道, ServiceWorker 的状态在结束/重启的循环中不是一直保持不变的,所以每个事件处理器应该设定一个默认的全局状态。

一旦成功地注册了service worker,为了节省内存和处理器,它将在他的状态达到了空闲的时候被终止。 一个在激活状态的service worker为了响应事件是可以自动重启的,就像这两个方法, {{domxref("ServiceWorkerGlobalScope.onfetch")}} 或者{{domxref("ServiceWorkerGlobalScope.onmessage")}}.

此外, 在service worker中, 同步请求是被禁止的 - 只有异步请求,如方法{{domxref("GlobalFetch.fetch", "fetch()")}} 才被允许.

该接口继承自 {{domxref("WorkerGlobalScope")}} 接口, 以及其父类 {{domxref("EventTarget")}}, 因此继承属性来自 {{domxref("WindowTimers")}}, {{domxref("WindowBase64")}}, 和 {{domxref("WindowEventHandlers")}}.

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

属性

{{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.onnotificationclose")}}
An event handler fired whenever a {{Event("notificationclose")}} event occurs — when a user closes 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. 

方法

{{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.

示例

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;
      }, function(error) {
        console.error('Fetching failed:', error);

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

规范

规范 状态 备注
{{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','#sync-event','onsync')}} {{Spec2('Background Sync')}} Adds the {{domxref("ServiceWorkerGlobalScope.onsync","onsync")}} event.

浏览器兼容性

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

[1] Service workers (and Push) have been disabled in the Firefox 45 and 52 Extended Support Releases (ESR.)

See also