How to tell if a waiting Service Worker is ready?

829 views Asked by At

According to the spec, the ServiceWorker.waiting property returns a reference to a service worker that is installed and waiting to be activated.

This is fine. But how do I find out when the waiting service worker has transitioned to a new state?

The service worker returned by ServiceWorker.waiting does not seem to have any of the necessary events for notifying state change:

if (registration.waiting) {

  registration.waiting.postMessage('skip-waiting');

  // This is failing because ready is undefined.
  registration.waiting.ready.then(function () {

    console.log('new service worker - ready');
 }
}
1

There are 1 answers

0
Zephyr was a Friend of Mine On BEST ANSWER

At the time of writing, registration.waiting.onstatechange is null in Chrome. However, the following works:

if (registration.waiting) {

  const waiting = registration.waiting;

  waiting.postMessage('skip-waiting');

  waiting.addEventListener('statechange', function (e) {

    if(waiting.state === 'activated') {
      console.log('new service worker - ready');
    }
 }
}