是否有可能从一个新服务工作者中检测到现有服务工作者的存在?

Is it possible to detect the presence of an existing service worker from within a new one?

我有一个复杂的 service worker。在安装时,它的初始设置行为需要更改,具体取决于是否已经有另一个 service worker 为 origin 准备就绪。

是否有可能从服务工作者内部检测,最好是在 install 事件期间,是否有另一个服务工作者已经处于活动状态?

从页面上下文来看,我似乎可以使用 navigator.serviceWorker.getRegistrations(),但是 navigator.serviceWorker 在 service worker 本身内部是未定义的。

假设您在两次部署之间不更改 URL 或 Service Worker 的范围,您应该能够从 self.registration.

中获取该信息
self.addEventListener('install', (event) => {
  const {installing, waiting, active} = self.registration;

  // Since we're in the install handler, `installing` should
  // be set to the SW whose global state is `self`.

  // `waiting` is likely to be `null`, unless there happened to be a SW
  // that was waiting to activate at the point this SW started install.

  // `active` is what you're most interested in. If it's null, then there
  // isn't already an active SW with the same registration info.
  // If it's set to a SW, then you know that there is one.
});