How To Point To Current Directory In Serviceworker.js

- 1 answer

I have my service worker installed on a staging directory

Main Website is on:

Staging is on:

Service Worker path:

This is how I register service worker:

navigator.serviceWorker.register('', {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 not

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.



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 = [

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 // it has a default scope of //