# 安全移除 service worker（kill switch）

> registration.unregister() 移除的是什么、已被控制的页面为何在卸载前仍由旧 worker 接管，以及替换用的 worker 如何清掉自己的缓存。

`ServiceWorkerRegistration.unregister()` 方法可以注销 Service Worker，用来修复 worker 持续返回旧缓存的问题。服务端修好后，worker 仍可能继续返回缓存，因为受控页面收到什么响应由 worker 决定。

## 工作原理

规范把取消注册和解除旧 worker 对页面的控制分成两步。页面无法决定后一步何时完成。

### unregister() 以什么值兑现

`unregister()` 不接受参数，返回一个 promise。找不到注册时该 promise 以 `false` 兑现，否则以 `true` 兑现，「irrespective of whether unregistration happened or not (it may not unregister if someone else just called `ServiceWorkerContainer.register()` with the same scope.)」；service worker 会先完成正在执行的操作，再注销（[ServiceWorkerRegistration: unregister() method](https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerRegistration/unregister)，developer.mozilla.org）。MDN 把这个方法记为 Baseline 广泛可用，自 2018 年 4 月起在各浏览器中可用，并且在部分或全部支持它的浏览器中仅在安全上下文可用。

规范的 `Unregister` 算法解释了为什么兑现值几乎说明不了结果。它按任务的 `storage key` 与 `scope url` 取出注册；若为 null，就以 false 兑现任务 promise 并结束。否则移除该键与 scope 对应的 `registration map` 条目，以 true 兑现任务 promise，再调用 `Try Clear Registration`（[Service Workers](https://w3c.github.io/ServiceWorker/)，w3c.github.io）。因此 `true` 报告的是映射条目已被移除，而不是 worker 已经停止。

### 已打开的页面为何仍留着旧 worker

清理是延后的。规范指出，当 `Try Clear Registration` 在那一步没有触发 `Clear Registration` 时，「Clear Registration is tried again when the last client using the registration is unloaded or the extend lifetime promises for the registration's service workers settle」。方法的注释还说明，受控客户端的活动 service worker 所属注册「is effective until all the service worker clients (including itself) using this service worker registration unload. That is, the `unregister()` method only affects subsequent navigations.」

kill switch 执行后，调用它的标签页仍由旧 worker 控制，后续 fetch 仍交给旧处理器。重新加载或关闭标签页，才能结束这份注册对它的影响。

### unregister() 不会移除什么

`Unregister` 算法处理 `registration map` 和注册下的 worker。清理缓存响应要用另一个接口。`CacheStorage.keys()` 返回的 Promise 兑现为字符串数组，按创建顺序列出 `CacheStorage` 跟踪的具名 `Cache` 对象（[CacheStorage: keys() method](https://developer.mozilla.org/en-US/docs/Web/API/CacheStorage/keys)，developer.mozilla.org），`CacheStorage.delete()` 则查找与 `cacheName` 匹配的 `Cache`，删除后以 `true` 兑现，找不到同名缓存时以 `false` 兑现（[CacheStorage: delete() method](https://developer.mozilla.org/en-US/docs/Web/API/CacheStorage/delete)，developer.mozilla.org）。已知缓存名称时，直接按列表删除即可；需要先查出名称时再调用 `keys()`。

`keys()` 会列出这个 `CacheStorage` 对象相关映射中的全部缓存名称，可能包含其他应用的缓存。只删除待移除应用拥有的缓存；示例用应用专属的名称前缀筛选。

## 示例

页面还能加载时，可以从页面注销 worker。如果旧 worker 连这份页面也返回旧缓存，就部署一个会自行注销的替代 worker。

### 移除当前客户端 storage key 下的每份注册

`navigator.serviceWorker.getRegistrations()` 以数组形式取回与某个 `ServiceWorkerContainer` 关联的全部 `ServiceWorkerRegistration` 对象（[ServiceWorkerContainer: getRegistrations() method](https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/getRegistrations)，developer.mozilla.org），因此即使当前页面不知道某个 worker 的 scope，也能用这次调用找到它。

```js
// 本应用创建的每个缓存都带这个名称前缀，所以这里只允许删掉
// 带该前缀的名字。
const OWNED_CACHE_PREFIX = 'app-';

async function removeAllWorkers() {
  if (!('serviceWorker' in navigator)) {
    // 该上下文没有 worker API：也就没有已注册的东西需要移除。
    return { supported: false, removed: 0 };
  }
  const registrations = await navigator.serviceWorker.getRegistrations();
  const results = await Promise.all(registrations.map((reg) => reg.unregister()));
  const names = await caches.keys();
  const owned = names.filter((name) => name.startsWith(OWNED_CACHE_PREFIX));
  await Promise.all(owned.map((name) => caches.delete(name)));
  return { supported: true, removed: results.filter(Boolean).length, cachesDeleted: owned.length };
}
```

不支持的分支返回一份结构化结果，因为当前上下文没有暴露 Service Worker API。旧 worker 会继续控制页面，直到页面卸载，所以调用方仍需重新加载这些页面。把前缀换成待移除 worker 实际使用的缓存前缀，将清理范围限制在本应用内。如果没有共同前缀，就明确列出要删除的缓存名称。

### 部署一个会把自己注销掉的 worker

如果旧 worker 连执行注销的页面也返回旧副本，就需要部署替代的 service worker。`self.registration` 返回指向该 worker 自身 `ServiceWorkerRegistration` 对象的引用（[ServiceWorkerGlobalScope: registration property](https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerGlobalScope/registration)，developer.mozilla.org），而 `skipWaiting()` 让新 worker 不必等旧 worker 的客户端关闭就能激活（[ServiceWorkerGlobalScope: skipWaiting() method](https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerGlobalScope/skipWaiting)，developer.mozilla.org）。

```js
// sw.js，用来顶替正在被移除的那个 worker
const OWNED_CACHE_PREFIX = 'app-';

self.addEventListener('install', () => {
  self.skipWaiting();
});

self.addEventListener('activate', (event) => {
  event.waitUntil((async () => {
    const names = await caches.keys();
    await Promise.all(
      names
        .filter((name) => name.startsWith(OWNED_CACHE_PREFIX))
        .map((name) => caches.delete(name)),
    );
    await self.registration.unregister();
  })());
});
```

这个脚本不注册 `fetch` 处理器，所以一旦它成为活动 worker，它的客户端在下一次导航时就走网络。注册本身由那次 `unregister()` 调用移除，按规范注释，最后一个使用该注册的客户端卸载后，才会清理所属的 worker。

:::caution
去掉那层过滤，也就是对 `caches.keys()` 的完整结果直接运行 `names.map((name) => caches.delete(name))`，会删除这个 `CacheStorage` 对象相关映射中的每个具名缓存，而不只是这个 worker 拥有的缓存。对 kill switch 本身来说，应把删除范围限制在该应用拥有的缓存名称内。当需要更广的清理时，[Clear-Site-Data](/zh/reference/storage/clearing-data/) 是由服务端驱动的手段。
:::

:::note
Chrome DevTools 在 Application › Service workers 中提供同一个操作。DevTools 前端的 `ServiceWorkersView.ts` 把按钮文字 `Unregister` 和提示文字 `Unregister Service Worker` 定义为 `UIStrings` 条目（[ServiceWorkersView.ts](https://chromium.googlesource.com/devtools/devtools-frontend/+/main/front_end/panels/application/ServiceWorkersView.ts)，chromium.googlesource.com）。
:::

## 另请参阅

- [ServiceWorkerRegistration: unregister() method](https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerRegistration/unregister)（developer.mozilla.org）
- [Service Workers](https://w3c.github.io/ServiceWorker/)（w3c.github.io）
- [CacheStorage: delete() method](https://developer.mozilla.org/en-US/docs/Web/API/CacheStorage/delete)（developer.mozilla.org）
- [skipWaiting() 与更新流程](/zh/reference/service-worker/update-skipwaiting/)
- [Service worker 生命周期](/zh/reference/service-worker/lifecycle/)
- [Clear-Site-Data 响应头](/zh/reference/storage/clearing-data/)
- [Service worker 调试](/zh/reference/service-worker/debugging/)