大网数据广告活动
Web 标准与前端开发

ServiceWorker

· 52CE 我爱测

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

Service Workers API

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

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

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

实例属性

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 的变化并且返回它的值。

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

规范

浏览器兼容性

参见

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。