检查ServiceWorker是否处于等待状态

Abh*_*oni 1 javascript service-worker

我试图了解Service Worker API,并且了解有关注册Service Worker的点点滴滴。

如API文档中所述,如果找到服务工作者更新,则会注册服务工作者并将其添加到队列中。当且仅当关闭并再次打开该页面时,此SW才接管页面。即,关闭窗口并再次重新打开。

现在,这有一些缺点,

1.用户可能看到的是以前的版本,可能存在非常严重的语法错误。管他呢。

  1. 需要以某种方式通知用户该内容已更改,并且需要进行引用。

我知道如何告诉SW.js跳过skip()并接管。以及如何向SW.js发送消息,告知用户用户希望自动刷新。

但是,我不知道如何知道新的SW是否实际上处于等待状态。

我用了这个:

navigator.serviceWorker.ready.then((a) => {
        console.log("Response, ", a);
        if (a.waiting !== null && a.waiting.state === "installed") {
            console.log("okay");
        }

    });
Run Code Online (Sandbox Code Playgroud)

但这通常将等待状态返回为null(可能是因为触发请求时SW仍在安装)。

我怎么知道客户端页面上有一个等待的软件?

Jef*_*ick 10

这是一些代码,它们将在有新的或更新的服务工作者注册时检测并允许您处理各种状态。

请注意,该日志消息假定skipWaiting()在服务程序的安装过程中未调用该消息。如果正在调用它,则不必关闭所有选项卡来激活新的Service Worker,它只会自动激活。

if ('serviceWorker' in navigator) {
  window.addEventListener('load', async function() {
    const registration = await navigator.serviceWorker.register('/service-worker.js');
    if (registration.waiting && registration.active) {
      // The page has been loaded when there's already a waiting and active SW.
      // This would happen if skipWaiting() isn't being called, and there are
      // still old tabs open.
      console.log('Please close all tabs to get updates.');
    } else {
      // updatefound is also fired for the very first install. ¯\_(?)_/¯
      registration.addEventListener('updatefound', () => {
        registration.installing.addEventListener('statechange', () => {
          if (event.target.state === 'installed') {
            if (registration.active) {
              // If there's already an active SW, and skipWaiting() is not
              // called in the SW, then the user needs to close all their
              // tabs before they'll get updates.
              console.log('Please close all tabs to get updates.');
            } else {
              // Otherwise, this newly installed SW will soon become the
              // active SW. Rather than explicitly wait for that to happen,
              // just show the initial "content is cached" message.
              console.log('Content is cached for the first time!');
            }
          }
        });
      });
    }
  });
}
Run Code Online (Sandbox Code Playgroud)