gpt4 book ai didi

service-worker - ServiceWorkerRegistration.active 首次未设置(Chrome)

转载 作者:行者123 更新时间:2023-12-02 21:04:24 25 4
gpt4 key购买 nike

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

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

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

最佳答案

对于您描述的第一次访问,当 promise 解析时,注册尚未事件,但它正在“安装”,因此注册的 installing 属性将返回服务人员。

由于没有服务工作线程处于等待状态,因此它将转换为激活,然后事件。所以你说得对,注册属性最初不是活跃,但刷新后就会活跃。

下面的代码将说明:

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

第一次访问时,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

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

关于service-worker - ServiceWorkerRegistration.active 首次未设置(Chrome),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36828088/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com