Search code examples
service-workerprogressive-web-appsworkbox

PWA Service Worker (Workbox) setting's '/' stand for?


I want to create PWA's service worker file by using workbox.
According to workbox document, precaching setting of workbox is something like this:

service-worker.js

workbox.precaching.precacheAndRoute([
  '/styles/example.ac29.css',
  { url: '/index.html', revision: 'abcd1234' },
  // ... other entries ...
]);

But what is the actual meaning of /index.html or /styles/example.ac29.css?
It is server root? or, the root of PWA's scope?

For example, if service-worker.js is served in https://example.com/hoge/fuga/service-worker.js, and manifest.json is also served in https://example.com/hoge/fuga/manifest.json with content:

{
  "name": "Great PWA site",
  "background_color": "#f6f0d3",
  "icons": [...],
  "start_url": "https://example.com/hoge/fuga/",
  "scope":"/hoge/fuga/",
  "display": "standalone"
}

In such case, /index.html in workbox setting means https://example.com/index.html? Or, https://example.com/hoge/fuga/index.html?


Solution

  • Within Workbox's precache manifest, /index.html is resolved to a full URL using the server root as the base. It does not user the service worker scope as the base. (After Googling, I guess it's technically called a "root-relative" URL, though I've never really used that phrase before.)

    If you had a relative URL like ./index.html, it would be resolved to a full URL using the location of the service worker script as the base.

    In general, if you're curious as to what a URL will resolve to, you can run the following from the ServiceWorkerGlobalScope to see:

    (new URL('some-URL.html', self.location.href)).href
    

    The easiest way to do this is to open up Chrome's DevTools while on a page you're curious about that has a service worker, go to the Console panel, and choose the service worker's scope in the popup menu, and then enter the code above.

    enter image description here