来自 ServiceWorker 的 http 请求是否来自注册时设置的范围?

Do the http requests from within a ServiceWorker not come form the scope set when registering?

我正在尝试像这样注册服务人员:

navigator.serviceWorker.register("/static/sw.js", {scope: "/blogs"});

目标是在 install 步骤中发出填充缓存的请求,如下所示:

cache.addAll([
  "/main.css",
  "/logo.png"
]);

将向缓存发出请求并将其保存到缓存中:

<website origin>/blogs/main.css
<website origin>/blogs/logo.png

然而,虽然注册范围似乎是正确的(浏览器开发工具的“应用程序”选项卡中的 ServiceWorker 显示了正确的路径),但发出的请求不包括 /blogs 部分。

在这种情况下,我无法将请求的 /blogs 部分硬编码为 cache.addAll,因为该值会根据部署阶段而变化。 SW 不知道将设置为 scope 的值,但 window 知道。

我认为来自 ServiceWorker 的请求必须通过注册时设置的范围,但事实并非如此。

如果我在 addAll 中省略 /,那么请求会像这样发出:

<website origin>/static/main.css
<website origin>/static/logo.png

因为 /static 是 Service Worker 所在的位置,目前,如果没有必要,我宁愿不将它移动到 /blogs。

您可以通过检查 self.registration.scope 值从 ServiceWorker 访问此范围值。
从那里您所要做的就是使用此值将资产的相对 URL 转换为绝对 URL。

cache.addAll([
  "./main.css",
  "./logo.png"
] // make them relative to the SW's scope
  .map((url) => new URL(url, registration.scope))
);