如何判断等待的 Service Worker 是否准备就绪?

How to tell if a waiting Service Worker is ready?

According to the specServiceWorker.waiting 属性 returns 对已安装并等待激活的 service worker 的引用。

这很好。但是我如何知道等待的 service worker 何时转换到新状态?

ServiceWorker.waiting 返回的 service worker 似乎没有任何通知状态更改的必要事件:

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');
 }
}

在撰写本文时,registration.waiting.onstatechange 在 Chrome 中为空。但是,以下工作:

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');
    }
 }
}