ServiceWorker 处理范围外 URL 的获取事件

Mar*_*ner 4 javascript offline offline-browsing service-worker

我的网站注册了一个 ServiceWorker,其范围仅限于以/sw/....

\n\n
 /**\n  * Register the Service Worker.\n  */\n if (\'serviceWorker\' in navigator) {\n     navigator.serviceWorker\n         .register(\'{{ URL::asset(\'sw/serviceworker.js\') }}\', {scope: \'./sw/\'})\n         .then(registration => {\n             console.log("SW registered. Scope: ", registration.scope);\n         }).catch(err => { console.error("SW Register failed: ", err); });\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

路径内的页面之一/sw/...执行对服务器的提取,以查看与服务器的连接是否可用。它获取的地址是/ping,一个返回一些 JSON 的简单页面。请注意,地址/ping/不在路径内/sw/...

\n\n
// Sample of the bit inside my promise that checks for the server\n// this is the request that is being cached\n\nfetch(\'/ping\')\n    .then(function(response) {\n\n        if (response.status == 200) {\n            console.log(\'%c Server available! \', \'background: #20c997; color: #000\');\n        }\n\n    })\n    .catch(function(err) {\n        console.log(\'fetch failed! \', err);\n    });\n
Run Code Online (Sandbox Code Playgroud)\n\n

然而浏览器清楚地显示 serviceWorker 拦截了对/ping.

\n\n

从 Google Chrome 开发控制台:

\n\n
\xe2\x96\xb6 Fetching http://127.0.0.1:8000/ping Request\xc2\xa0{method: "GET", url: "http://127.0.0.1:8000/ping", headers: Headers, referrer: "http://127.0.0.1:8000/sw/create", referrerPolicy: "no-referrer-when-downgrade",\xc2\xa0\xe2\x80\xa6} serviceworker.js:105 \n\xe2\x96\xb6 Fetched over network http://127.0.0.1:8000/ping:  Response\xc2\xa0{type: "basic", url: "http://127.0.0.1:8000/ping", redirected: false, status: 200, ok: true,\xc2\xa0\xe2\x80\xa6} \n
Run Code Online (Sandbox Code Playgroud)\n\n

这没有达到我的预期,因为我只希望 ServiceWorker 拦截以以下地址开头的请求:/sw/...

\n\n

ServiceWorkers 的规范或预期行为中是否有某处表明它可以缓存对范围内页面发出的获取事件的响应,即使它所访问的地址超出范围?

\n

Mar*_*ner 6

回答我自己的问题...

是的,这有意的行为。范围不是由提取的地址决定的,而是由发出请求的页面的地址决定的。

谷歌指南中的这段引用中的关键词是“来自” :

...它将处理从页面发出网络请求或消息时发生的获取和消息事件。

因此,如果 JavaScript/sw/page1.html发出fetch()请求,/ping则 ServiceWorker 会将其视为“在范围内”,因为发送请求的页面以/sw/....

范围还包括浏览器发出的获取页面的原始请求。因此,如果浏览器尝试导航到以 开头的页面,/sw/...并且注册了 ServiceWorker,那么它将处理该请求。