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 |
瀏覽器相容性
載入中…