FetchEvent

Baseline 廣泛可用 *

此功能已成熟,可跨多種裝置和瀏覽器版本工作。它自 ⁨2018 年 4 月⁩ 起已在所有瀏覽器中可用。

* 此特性的某些部分可能存在不同級別的支援。

注意:此功能僅在 Service Workers 中可用。

這是在service worker global scope上分派的 fetch 事件的事件型別。它包含有關 fetch 的資訊,包括請求以及接收方將如何處理響應。它提供了 event.respondWith() 方法,使我們能夠為此 fetch 提供一個響應。

Event ExtendableEvent FetchEvent

建構函式

FetchEvent()

建立一個新的 FetchEvent 物件。通常不使用此建構函式。瀏覽器會建立這些物件並將它們提供給 fetch 事件回撥。

例項屬性

繼承自其祖先 Event 的屬性.

FetchEvent.clientId 只讀

發起 fetch 的同源 clientid

FetchEvent.handled 只讀

一個在事件尚未處理時處於掛起狀態,並在處理完成後 fulfilled 的 Promise。

FetchEvent.isReload 只讀 已棄用 非標準

如果事件是由使用者嘗試重新載入頁面觸發的,則返回 true,否則返回 false

FetchEvent.preloadResponse 只讀

一個 Promise,用於獲取 Response,如果此 fetch 不是導航,或者 導航預載入未啟用,則為 undefined

FetchEvent.replacesClientId 只讀

在頁面導航期間被替換的 clientid

FetchEvent.resultingClientId 只讀

在頁面導航期間替換前一個 client 的 clientid

FetchEvent.request 只讀

瀏覽器打算發起的 Request

例項方法

繼承自其父級 ExtendableEvent 的方法.

FetchEvent.respondWith()

阻止瀏覽器的預設 fetch 處理,並自己提供(一個 Promise 形式的)響應。

ExtendableEvent.waitUntil()

延長事件的生命週期。用於通知瀏覽器執行超出返回響應的任務,例如流式傳輸和快取。

示例

此 fetch 事件對於非 GET 請求使用瀏覽器預設值。對於 GET 請求,它嘗試在快取中查詢匹配項,然後回退到網路。如果在快取中找到匹配項,它將非同步更新快取以備下次使用。

js
self.addEventListener("fetch", (event) => {
  // Let the browser do its default thing
  // for non-GET requests.
  if (event.request.method !== "GET") return;

  // Prevent the default, and handle the request ourselves.
  event.respondWith(
    (async () => {
      // Try to get the response from a cache.
      const cache = await caches.open("dynamic-v1");
      const cachedResponse = await cache.match(event.request);

      if (cachedResponse) {
        // If we found a match in the cache, return it, but also
        // update the entry in the cache in the background.
        event.waitUntil(cache.add(event.request));
        return cachedResponse;
      }

      // If we didn't find a match in the cache, use the network.
      return fetch(event.request);
    })(),
  );
});

規範

規範
Service Workers
# fetchevent-interface

瀏覽器相容性

另見