Home > Back-end >  Do the http requests from within a ServiceWorker not come form the scope set when registering?
Do the http requests from within a ServiceWorker not come form the scope set when registering?

Time:03-08

I am trying to register a service worker like so:

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

With the goal to make requests to fill the cache during the install step like so:

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

the requests would be made to and be saved to the cache as:

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

However, while the scope of the registration seems to be correct (the ServiceWorker in the Application tab of the browser dev tools shows the correct path) the requests made don't include the /blogs part.

In this scenario I cant hardcode the /blogs part of the request to cache.addAll because the value will change depending on deployment stage. The SW wont know the value that will be set to scope, but the window will.

I thought the requests that come from a ServiceWorker will have to go thru the scope set on registration but that doesn't seem to be the case.

If I omit the / in addAll then the requests are made like so:

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

since /static is where the Service Worker resides and, currently, I would rather not move it to /blogs if I don't have to.

CodePudding user response:

You can access this scope value from your ServiceWorker by checking the self.registration.scope value.
From there all you have to do is to convert your assets's relative URLs to absolute ones by using this value.

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