ServiceWorker

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since April 2018.

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

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

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

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

EventTarget ServiceWorker

实例属性

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

ServiceWorker.scriptURL 只读

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

ServiceWorker.state 只读

返回 service worker 的状态。其值可能是如下之一:installinginstalledactivatingactivatedredundant

实例方法

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

规范

Specification
Service Workers
# serviceworker-interface

浏览器兼容性

BCD tables only load in the browser

参见