首页 > 解决方案 > 是否可以从新的服务人员中检测到现有服务人员的存在?

问题描述

我有一个复杂的服务人员。在安装时,它的初始设置行为需要根据是否已经有另一个服务工作者为源站准备就绪而改变。

是否可以从服务人员内部(最好是在install事件期间)检测另一个服务人员是否已经处于活动状态?

从页面上下文中看起来我可以使用navigator.serviceWorker.getRegistrations(),但navigator.serviceWorker在服务工作者本身内部是未定义的。

标签: javascriptservice-worker

解决方案


假设您没有在部署之间更改服务工作者的 URL 或范围,您应该能够从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.
});

推荐阅读