Service-Worker-Allowed header
HTTP Service-Worker-Allowed 響應頭用於放寬服務工作執行緒預設 scope 的路徑限制。
預設情況下,服務工作執行緒註冊的 scope 是服務工作執行緒指令碼所在的目錄。例如,如果指令碼 sw.js 位於 /js/sw.js 中,則預設情況下它只能控制 /js/ 下的 URL。伺服器可以使用 Service-Worker-Allowed 頭來允許服務工作執行緒控制其自身目錄之外的 URL。
服務工作執行緒會攔截其作用域內的所有網路請求,因此除非必要,否則應避免使用過於寬泛的作用域。
語法
http
Service-Worker-Allowed: <scope>
指令
<scope>-
一個字串,表示定義服務工作執行緒註冊作用域的 URL;即服務工作執行緒可以控制的 URL 範圍。
示例
使用 Service-Worker-Allowed 擴大服務工作執行緒的作用域
下面的 JavaScript 示例包含在 example.com/product/index.html 中,並嘗試 註冊 一個服務工作執行緒,其作用域適用於 example.com/ 下的所有資源。
js
navigator.serviceWorker.register("./sw.js", { scope: "/" }).then(
(registration) => {
console.log("Install succeeded, scoped to '/'", registration);
},
(error) => {
console.error(`Service worker registration failed: ${error}`);
},
);
對服務工作執行緒指令碼資源請求(./sw.js)的 HTTP 響應包括設定為 / 的 Service-Worker-Allowed 頭。
http
HTTP/1.1 200 OK
Date: Mon, 16 Dec 2024 14:37:20 GMT
Service-Worker-Allowed: /
// sw.js contents…
如果伺服器未設定此頭,則服務工作執行緒註冊將失敗,因為 scope 選項({ scope: "/" })請求的作用域比服務工作執行緒指令碼所在的目錄(/product/sw.js)更寬泛。
規範
| 規範 |
|---|
| Service Workers # service-worker-allowed |
瀏覽器相容性
載入中…