此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

View in English Always switch to English

ServiceWorker

基线
广泛可用
*

自 2018年4月 起,此特性已在主流浏览器中得到支持,可在大多数设备和浏览器版本中正常使用。

* 此特性的某些部分的支持程度可能有所不同。

安全上下文: 此特性仅在一些支持的浏览器的安全上下文(HTTPS)中可用。

Service Worker API 的 ServiceWorker 接口提供了对 service worker 的引用。各个浏览上下文(例如页面、worker 等)可以与相同的 service worker 相关联,每个浏览上下文都可以通过唯一的 ServiceWorker 对象访问。

在 ServiceWorkerRegistration.active 属性和 ServiceWorkerContainer.controller 属性中有一个 ServiceWorker 对象——这是一个已激活并在控制页面的 service worker(service worker 成功注册,被控页面已经重新加载)。

ServiceWorker 接口被分配了一系列生命周期事件——install 和 activate——以及功能型的事件,包括 fetch。一个 ServiceWorker 对象有一个与之关联的 ServiceWorker.state,指示着它的生命周期。

EventTarget ServiceWorker

实例属性

ServiceWorker 接口继承其父类 EventTarget 的属性。

ServiceWorker.scriptURL 只读

返回作为 ServiceWorkerRegistration 一部分所定义的 ServiceWorker 序列化脚本 URL。这个 URL 必须和注册该 ServiceWorker 的文档处于同一域。

ServiceWorker.state 只读

返回 service worker 的状态。其值可能是如下之一:installing、installed、activating、activated 或 redundant。

实例方法

ServiceWorker 接口继承其父类 EventTarget 的方法。

事件

ServiceWorker.onstatechange 只读

每当 ServiceWorker.state 发生改变时,都会触发。

示例

代码段来自 service worker registration-events sample(在线演示)。这段代码监听了 ServiceWorker.state 的变化并且返回它的值。

js
if ("serviceWorker" in navigator) {
  navigator.serviceWorker
    .register("service-worker.js", {
      scope: "./",
    })
    .then((registration) => {
      let serviceWorker;
      if (registration.installing) {
        serviceWorker = registration.installing;
        document.querySelector("#kind").textContent = "installing";
      } else if (registration.waiting) {
        serviceWorker = registration.waiting;
        document.querySelector("#kind").textContent = "waiting";
      } else if (registration.active) {
        serviceWorker = registration.active;
        document.querySelector("#kind").textContent = "active";
      }
      if (serviceWorker) {
        // logState(serviceWorker.state);
        serviceWorker.addEventListener("statechange", (e) => {
          // logState(e.target.state);
        });
      }
    })
    .catch((error) => {
      // Something went wrong during registration. The service-worker.js file
      // might be unavailable or contain a syntax error.
    });
} else {
  // The current browser doesn't support service workers.
  // Perhaps it is too old or we are not in a Secure Context.
}

规范

规范
Service Workers Nightly
# serviceworker-interface

浏览器兼容性

参见