CacheStorage: match() 方法
注意:此功能在 Web Workers 中可用。
CacheStorage 接口的 match() 方法用于检查给定的 Request 或 URL 字符串是否是已存储的 Response 的键。此方法返回一个 Promise,该 Promise 解析为一个 Response,如果没有找到匹配项,则解析为 undefined。
您可以通过窗口中的 Window.caches 属性或在 worker 中的 WorkerGlobalScope.caches 属性来访问 CacheStorage。
Cache 对象按创建顺序进行搜索。
注意: caches.match() 是一个便捷方法。等效的功能是按顺序(由 caches.keys() 返回的顺序)在每个缓存上调用 cache.match(),直到返回 Response。
语法
match(request)
match(request, options)
参数
请求options可选-
一个对象,其属性控制
match操作中的匹配方式。可用选项包括:ignoreSearch-
一个布尔值,指定匹配过程是否应忽略 URL 中的查询字符串。例如,如果设置为
true,在执行匹配时将忽略http://foo.com/?value=bar中的?value=bar部分。默认为false。 ignoreMethod-
一个布尔值,如果设置为
true,则阻止匹配操作验证Request的http方法(通常只允许GET和HEAD)。默认为false。 ignoreVary-
一个布尔值,如果设置为
true,则指示匹配操作不执行VARY头部匹配。换句话说,如果 URL 匹配,无论Response对象是否有VARY头部,都会找到匹配项。默认为false。 cacheName-
一个字符串,表示要搜索的特定缓存。
返回值
一个 Promise,解析为匹配的 Response。如果未找到与指定请求匹配的响应,则 Promise 会解析为 undefined。
示例
此示例来自 MDN 的 简单 service worker 示例(参见 正在运行的简单 service worker)。在这里,我们等待 FetchEvent 触发。我们像这样构建一个自定义响应:
- 使用
CacheStorage.match()检查是否在CacheStorage中找到了请求的匹配项。如果是,则提供该匹配项。 - 如果不是,则使用
open()打开v1缓存,使用Cache.put()将默认网络请求放入缓存,并使用return response.clone()返回默认网络请求的克隆。后者是必需的,因为put()会消耗响应体。 - 如果失败(例如,因为网络中断),则返回一个备用响应。
self.addEventListener("fetch", (event) => {
event.respondWith(
caches.match(event.request).then((response) => {
// caches.match() always resolves
// but in case of success response will have value
if (response !== undefined) {
return response;
}
return fetch(event.request)
.then((response) => {
// response may be used only once
// we need to save clone to put one copy in cache
// and serve second one
let responseClone = response.clone();
caches
.open("v1")
.then((cache) => cache.put(event.request, responseClone));
return response;
})
.catch(() => caches.match("/gallery/myLittleVader.jpg"));
}),
);
});
规范
| 规范 |
|---|
| Service Workers # cache-storage-match |
浏览器兼容性
加载中…