3
votes

I've got a web-app thats deployed to the non root path of a static server. That is MyApp when built is deployed to a path/folder https://example.com/myapp.

MyApp is using vue and webpack so I've added the GenerateSW workbox plugin with the standard config. It's registering, adding all the files I need to the cache, but it's not being used.

My service worker is registering with scriptURL https://example.com/myapp/service-worker.js and scope https://example.com/myapp/. My cache storage has my files /myapp/index.html?__WB_REVISION_... /myapp/app.<hash>.js?__WB_REVISION_.. and so on. However the service worker is still not controlling the page, ie navigator.serviceWorker.controller is returning null.

I've seen this https://developers.google.com/web/tools/workbox/guides/troubleshoot-and-debug#common_problems but unlike in this situation I don't want the service worker having the root scope.

Am I missing any config options?

1

1 Answers

0
votes

controlling is sometimes null depending on where you are in the service worker lifecycle. When controlling is null you listen for the controllerchange event on the serviceworker object. My code just assumes everything is ok when the controllerchange event is dispatched, but you could check for serviceWorker.controller !== null before invoking the resolve method.

const controllerPromise = window.navigator.serviceWorker
  .register('https://example.com/myapp/service-worker.js')
  .then(() => window.navigator.serviceWorker.ready)
  .then(() => {
    if (window.navigator.serviceWorker.controller) {
      return Promise.resolve(window.navigator.serviceWorker.controller);
    }
    return new Promise(resolve =>
      window.navigator.serviceWorker
        .addEventListener('controllerchange', () => resolve(window.navigator.serviceWorker.controller))
    );
  })