Search code examples
clientes6-promiseprogressive-web-appsservice-workerregistration

Test for an active service worker from within the client


From within my client.js, I register a service worker with:

var someVariable;

if('serviceWorker' in navigator) {
    navigator.serviceWorker.register('./service-worker.js')
    .then(function() {
        console.log('Service worker registered.');
        if(localStorage.someVariable) {
            someVariable = JSON.parse(localStorage.someVariable);
        };
    });
};

Now, further down my client.js code, I would like to check whether client.js has an active service worker up and running.

Doing so from within service-worker.js would somewhat correspond to testing for self.registration, as self.registration.active does not seem to work.

However, what would be the equivalent test for an active service worker from within client.js?

navigator.serviceWorker.ready retuns a Promise, but I do not know if this is really what I need for use in/as a conditional.


Solution

  • Your options

    If you want to check whether the current page is under the control of some service worker at the current moment, you can examine navigator.serviceWorker.controller. It will be null if the current page is not controlled by a service worker, and set to a ServiceWorker instance if it is controlled by one.

    If you want to check if the service worker associated with a given ServiceWorkerRegistration is active at a given point in time, you can do that with code like:

    const registration = await navigator.serviceWorker.register('sw.js');
    // Examine `registration.active` to see if, at the current point in time,
    // there's an active service worker.
    

    If you want to write code that will wait until there's any active service worker associated with the current page's service worker registration, then await navigator.serviceWorker.ready will do that for you.

    active vs. controlling

    Just a quick note on the difference between an active service worker, and a controlling service worker. A service worker can be active but not in control of any client pages—this is what would happen the first time a service worker is registered for a given scope if the service worker doesn't call clients.claim().

    If you are calling clients.claim() in your service worker, then the distinction between active and controlling can mostly be ignored.