Search code examples
progressive-web-appsworkbox

Google Workbox Change Scope?


Here is my service worker:

// This is the "Offline page" service worker

importScripts('https://storage.googleapis.com/workbox-cdn/releases/5.1.2/workbox-sw.js');

const CACHE = "pwabuilder-page";

// TODO: replace the following with the correct offline fallback page i.e.: const offlineFallbackPage = "offline.html";
const offlineFallbackPage = "/error/404.html";

self.addEventListener("message", (event) => {
  if (event.data && event.data.type === "SKIP_WAITING") {
    self.skipWaiting();
  }
});

self.addEventListener('install', async (event) => {
  event.waitUntil(
    caches.open(CACHE)
      .then((cache) => cache.add(offlineFallbackPage))
  );
});

if (workbox.navigationPreload.isSupported()) {
  workbox.navigationPreload.enable();
}

self.addEventListener('fetch', (event) => {
  if (event.request.mode === 'navigate') {
    event.respondWith((async () => {
      try {
        const preloadResp = await event.preloadResponse;

        if (preloadResp) {
          return preloadResp;
        }

        const networkResp = await fetch(event.request);
        return networkResp;
      } catch (error) {

        const cache = await caches.open(CACHE);
        const cachedResp = await cache.match(offlineFallbackPage);
        return cachedResp;
      }
    })());
  }
});

the service worker is stored at /src/pwa/sw.js

How can i allow the scope of the service worker to run at / instead of /src/pwa/ ?

i use a Dynamic JS loader to load all of my javascript files, when i try to load the PWA loader, it says "scope of /src/pwa/ error"


Solution

  • The maximal scope of a service worker is determined by the location of your service worker script file. You mention that your script is being served from /src/pwa/sw.js, so the maximal scope is /src/pwa/.

    You need to register your service worker when it's hosted at /sw.js if you want the scope to be able to control all pages on your site.

    There's more background at Understanding Service Worker scope