使用 Service Worker Static 轉送 API,針對特定路徑略過 Service Worker

自 Chrome 123 起,Service Worker 靜態轉送 API 可供使用。這個 API 可讓您宣告應如何擷取特定資源路徑,也就是說,瀏覽器不需要執行 Service Worker,就能從快取或直接從網路擷取回應。這項 API 自 Chrome 116 起開始進行來源試用,本文將詳細說明 Chrome 123 中推出的 API。

使用 API

如要使用 API,請在服務工作人員 install 事件上呼叫 event.addRoutes。將路徑清單傳遞至這個方法,並包含下列屬性:

condition
指定規則的適用時間。接受下列屬性:
  • urlPatternURLPattern 執行個體,或代表有效 URLPattern 的字串,可傳遞至 URLPattern 建構函式。
  • requestMethod:包含要求方法的字串。
  • requestMode:包含要求模式的字串。
  • requestDestination:包含要求目的地的字串。
  • runningStatus:字串,可以是 "running""not-running"。這表示 Service Worker 的執行狀態。
source
指定如何載入與 condition 相符的資源。下列其中一個字串:
  • "network"
  • "cache"
  • "fetch-event"
  • "race-network-and-fetch-handler"

在下列範例中,如果服務工作站目前正在執行,系統會將以「/articles」開頭的網址路由至服務工作站。如有 urlPatternrunningStatus 等多個條件,則必須符合所有條件,系統才會使用該路徑。

addEventListener('install', (event) => {
  event.addRoutes({
    condition: {

          urlPattern: "/articles/*",
          runningStatus: "running"
    },
    source: "fetch-event"
  });
});

在下列範例中,表單的貼文會直接傳送至網路,並略過服務工作人員。

addEventListener('install', (event) => {
  event.addRoutes({
    condition: {
          urlPattern: "/form/*",
          requestMethod: "post"
    },
    source: "network"
  });
});

在下列範例中,名為 "pictures" 的快取儲存空間用於擷取副檔名為 .png.jpg 的檔案。

addEventListener('install', (event) => {
  event.addRoutes({
    condition: {
      or: [
        {urlPattern: "*.png"},
        {urlPattern: "*.jpg"}
      ]
    },
    source: {
      cacheName: "pictures"
    }
  });
});

與來源試用版不同的變更

原始的來源試用期使用 InstallEvent.registerRouter() 而非 InstallEvent.addRoutes(),因此 registerRouter() 方法只能呼叫一次。這項異動是根據社群對原始試用的意見回饋

新版 API 也採用 Chrome 121 中導入的 URLPattern 變更,可指定要求方法、模式和目的地,並新增其他來源選項。

Chrome 開發人員工具支援

註冊的路由器規則會顯示在「應用程式」面板的「Service Worker」分頁中。

應用程式面板中醒目顯示的路由器規則。

在「網路」面板中,如果要求符合已註冊的規則,大小欄中就會顯示相關資訊。將指標懸停在「大小」欄上時,系統會顯示已註冊的路由器 ID。應用程式分頁會顯示相應規則。

網路面板中顯示的路由器 ID。