FetchEvent: respondWith() 方法
Baseline 廣泛可用 *
注意:此功能僅在 Service Workers 中可用。
FetchEvent 的 respondWith() 方法會阻止瀏覽器的預設 fetch 處理,並允許您自己提供一個 的 Promise。Response
在大多數情況下,您可以提供接收方能夠理解的任何響應。例如,如果一個 發起了請求,響應體就需要是影像資料。出於安全原因,有一些全域性規則。<img>
- 只有當
物件的fetchEvent.request為mode"no-cors"時,您才能返回型別為"opaque"的物件。這可以防止私有資料洩露。Response - 只有當
物件的fetchEvent.request為mode"manual"時,您才能返回型別為"opaqueredirect"的物件。Response - 當
物件的fetchEvent.request為mode"same-origin"時,您不能返回型別為"cors"的物件。Response
指定資源的最終 URL
從 Firefox 59 開始,當 service worker 為 FetchEvent.respondWith() 提供 時,Response 值將被傳播到被攔截的網路請求中,作為最終解析的 URL。如果 Response.url 值是空字串,則使用 Response.url 作為最終 URL。FetchEvent.request.url
過去,在所有情況下, 都被用作最終 URL。提供的 FetchEvent.request.url 被有效忽略。Response.url
這意味著,例如,如果 service worker 攔截了一個樣式表或 worker 指令碼,那麼提供的 將用於解析任何相對的 Response.url 或 @import 子資源載入(Firefox bug 1222008)。importScripts()
對於大多數型別的網路請求,此更改沒有影響,因為您無法觀察到最終 URL。但有一些情況,它確實很重要。
- 如果攔截了
,那麼您可以在結果的fetch()上觀察到最終 URL。Response.url - 如果攔截了 worker 指令碼,那麼最終 URL 用於設定
,並用作 worker 指令碼中相對 URL 的基礎 URL。self.location - 如果攔截了樣式表,那麼最終 URL 將用作解析相對
載入的基礎 URL。@import
請注意, 和 Window 的導航請求不使用最終 URL。HTML 規範處理導航重定向的方式最終會將請求 URL 用於生成的 iframe。這意味著網站仍然可以在離線時提供網頁的“備用”檢視,而不會更改使用者可見的 URL。Window.location
語法
respondWith(response)
引數
返回值
無(undefined)。
異常
NetworkErrorDOMException-
當
和FetchEvent.request.mode值出現某些組合時,會觸發網路錯誤,如上面“全域性規則”中所提示。返回此錯誤。Response.type InvalidStateErrorDOMException-
如果事件尚未分派或
respondWith()已被呼叫,則返回此值。
示例
此 fetch 事件嘗試從快取 API 返回響應,否則回退到網路。
addEventListener("fetch", (event) => {
// Prevent the default, and handle the request ourselves.
event.respondWith(
(async () => {
// Try to get the response from a cache.
const cachedResponse = await caches.match(event.request);
// Return it if we found one.
if (cachedResponse) return cachedResponse;
// If we didn't find a match in the cache, use the network.
return fetch(event.request);
})(),
);
});
注意: 是一個方便的方法。等效的功能是按順序(由 caches.match() 返回的順序)在每個快取上呼叫 caches.keys(),直到返回 cache.match()。Response
規範
| 規範 |
|---|
| Service Workers # fetch-event-respondwith |
瀏覽器相容性
載入中…