ServiceWorkerRegistration.active 首次未设置(Chrome)

cod*_*ead 2 service-worker

在 Chrome Mac 上。我正在尝试注册一个 ServiceWorker 并为其设置一个变量。当我调用 register() 并且服务工作线程之前尚未安装时,“active”属性似乎立即设置为 null,然后很快就被初始化(异步?)。

var sw = null;
navigator.serviceWorker.register('preview/sw.js', {scope: 'preview/'}).
    then(function(registration) {
        console.dir(registration);
        sw = registration.active;
        if (!sw) {
          console.log('wat');
          console.dir(registration);
        }
    });
Run Code Online (Sandbox Code Playgroud)

换句话说,我第一次安装 Service Worker 时就进入了 if 块。控制台显示 active 属性设置为等于两个 console.dir() 命令中的 ServiceWorker,但 sw 变量为 null。

刷新页面即可解决问题。有人知道这可能是什么原因造成的吗?

ros*_*sta 5

对于您描述的第一次访问,当该承诺解决时,注册尚未active完成,但它正在“安装”,因此注册的installing属性将返回一个服务工作者。

由于没有 Service Worker 处于该waiting状态,因此它将转换到activatingthen active。所以你是对的,注册属性最初不是,active但在刷新时,它就会。

下面的代码将说明:

navigator.serviceWorker.register('/serviceworker.js').then(onRegistration);

function onRegistration(registration) {
  if (registration.waiting) {
    console.log('waiting', registration.waiting);
    registration.waiting.addEventListener('statechange', onStateChange('waiting'));
  }

  if (registration.installing) {
    console.log('installing', registration.installing);
    registration.installing.addEventListener('statechange', onStateChange('installing'));
  }

  if (registration.active) {
    console.log('active', registration.active);
    registration.active.addEventListener('statechange', onStateChange('active'));
  }
}

function onStateChange(from) {
  return function(e) {
    console.log('statechange initial state ', from, 'changed to', e.target.state);
  }
}
Run Code Online (Sandbox Code Playgroud)

第一次访问时,console.log输出将是:

installing ServiceWorker {scriptURL: "http://...", state: "installing", onstatechange: null, onerror: null}
statechange initial state installing changed to installed
statechange initial state installing changed to activating
statechange initial state installing changed to activated
Run Code Online (Sandbox Code Playgroud)

正如您所观察到的,状态更改是异步发生的。