Search code examples
service-workerworkbox

workbox: Set debug mode dynamically


Library Affected: workbox.setConfig

Browser & Platform: "all browsers".*

Issue or Feature Request Description: I am planning to set debug mode : true here is the process i am following :

  1. using PWA to store the mode value : true/false in a cache
  2. Opening the cache and set the debug value using the stored variable.
  3. the problem is everything is async and install event is getting called before workbox.setconfig

Does anyone know any workaround for this


Solution

  • The various workbox.* methods need to be executed synchronously at service worker startup, in order to load the required runtime bundles and establish the proper event listeners before events start firing. You're not going to be able to do anything asynchronous, like read from the Cache Storage API or IndexedDB, prior to initializing Workbox.

    I don't know how much flexibility you need in terms of toggling whether Workbox is in debug mode or not, but maybe the following would help. It allows you to use a URL query parameter to determine whether a given service worker registration will trigger Workbox's debug mode or not.

    // Inside your service worker,
    // before you make any other calls to workbox.* methods.
    
    const url = new URL(location.href);
    const debug = url.searchParams.has('debug');
    workbox.setConfig({debug});
    

    and then when you register:

    // To enable debugging:
    navigator.serviceWorker.register('/service-worker.js?debug');
    // To run without debugging:
    // navigator.serviceWorker.register('/service-worker.js');
    

    You might already know this, but Workbox will automatically switch into debug: true mode when it detects it's running on localhost, and run in production mode by default otherwise.