Search code examples
service-workerworkbox

How to point to current directory in serviceworker.js


I have my service worker installed on a staging directory

Main Website is on: https:example.com

Staging is on: https:example.com/test/

Service Worker path: https:example.com/test/serviceworker.js

This is how I register service worker:

navigator.serviceWorker.register('https:example.com/test/serviceworker.js', {scope: '/test/'})
.then(registration => {
  console.log(`Service Worker registered! Scope: ${registration.scope}`);
})

Service worker works just fine, and is installed.

My concern is that inside serviceworker.js I want to use the / to point to the path of the current directory automatically, which is in this case: /staging/

For example when I want to cache the homepage in my staging site

/**
 * Cache the homepage.
 */
workbox.routing.registerRoute('/', workbox.strategies.staleWhileRevalidate();

Here its caching https:example.com not https:example.com/test/

I know I can simply change registerRoute('/') to registerRoute('/staging/)'

But that is not efficient, and will make me need to have different version of the serviceworker for localhost, staging, and deployment. I want to know what's the right way to do it here, so I can set the scope '/' to the current directory that the serviceworker.js is in. Thank you.


Solution

  • Ok I think I figured how to do it the right way.

    How to point to current directory: simply './' Instead of '/'

    /**
     * Cache the homepage.
     */
    workbox.routing.registerRoute('./', workbox.strategies.staleWhileRevalidate();
    

    How to cache files and images in current path: './image/' instead of '/image/'

    const urlsToCache = [
      './image/fallback.png',
      './offline/'
    ];
    

    Now the same file works the same locally and on staging. This is such a newbie mistake, I need to be more clever :)

    Edit: I found this in Google documentation (The Service Worker Lifecycle):

    The default scope of a service worker registration is ./ relative to the script URL. This means if you register a service worker at //example.com/foo/bar.js it has a default scope of //example.com/foo/.