CacheStorage.delete()

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.

实验性: 这是一项实验性技术
在将其用于生产之前,请仔细检查浏览器兼容性表格

CacheStorage 接口的 delete() 方法查找匹配 cacheNameCache 对象。如果找到,则删除 Cache 对象,则返回的 Promise 兑现为 true;如果未找到 Cache 对象,则兑现为 false

你可以通过窗口的 Window.caches 属性或 worker 的 WorkerGlobalScope.caches 属性访问 CacheStorage

语法

js
delete(cacheName)

参数

cacheName

想要删除的缓存对象的名称。

返回值

一个 Promise,如果找到 Cache 对象,并成功删除,则兑现为 true;否则,兑现为 false

示例

在此代码片段中,我们等待一个 activate 事件,然后运行一个 waitUntil() 块,其在一个新的 service worker 被激活前清除所有旧的、未使用的 cache. 这里我们有一个白名单,其中包含我们想要保留的 cache 的 name. 我们使用 CacheStorage.keys 返回 CacheStorage 对象中 cache 的键,然后检查每个键值,以查看它是否在白名单中。如果没有,我们使用 delete() 删除它。

js
this.addEventListener("activate", function (event) {
  var cacheWhitelist = ["v2"];

  event.waitUntil(
    caches.keys().then(function (keyList) {
      return Promise.all(
        keyList.map(function (key) {
          if (cacheWhitelist.indexOf(key) === -1) {
            return caches.delete(key);
          }
        }),
      );
    }),
  );
});

规范

Specification
Service Workers
# cache-storage-delete

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobileserver
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
Deno
delete

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

参见