gpt4 book ai didi

javascript - Service Worker 安装成功后更新 UI

转载 作者:行者123 更新时间:2023-11-28 11:50:52 25 4
gpt4 key购买 nike

看起来 Service Worker 在工作线程上下文中运行,并且无法访问 DOM。但是,一旦安装了 Service Worker,我希望我的用户知道该应用程序现在可以离线工作。我怎样才能做到这一点?

最佳答案

当 Service Worker 处于激活状态时,这是显示 Toast“内容已缓存以供离线使用”的最佳时机。在注册您的 Service Worker 时尝试以下代码。

if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/service-worker.js').then(function(reg) {
// updatefound is fired if service-worker.js changes.
reg.onupdatefound = function() {
var installingWorker = reg.installing;

installingWorker.onstatechange = function() {
switch (installingWorker.state) {
case 'installed':
if (navigator.serviceWorker.controller) {
// At this point, the old content will have been purged and the fresh content will
// have been added to the cache.
// It's the perfect time to display a "New content is available; please refresh."
// message in the page's interface.
console.log('New or updated content is available.');
} else {
// At this point, everything has been precached.
// It's the perfect time to display a "Content is cached for offline use." message.
console.log('Content is now available offline!');
}
break;

case 'redundant':
console.error('The installing service worker became redundant.');
break;
}
};
};
}).catch(function(e) {
console.error('Error during service worker registration:', e);
});
}

关于javascript - Service Worker 安装成功后更新 UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37691011/

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