看起来 Service Worker 在工作人员上下文中运行并且无权访问 DOM。但是,一旦安装了 Service Worker,我希望我的用户知道该应用程序现在可以离线工作。我怎样才能做到这一点?
问问题
1498 次
2 回答
6
当 Service Worker 处于 时activated state
,这是显示 toast ' Content is cached for offline use
' 的最佳时机。在注册服务人员时尝试以下代码。
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);
});
}
于 2016-06-08T06:27:49.813 回答
2
在上面测试了@Prototype Chain的答案之后,我想使用named functions
而不是嵌套anonymous functions
作为事件处理程序,以使代码更符合我的口味,并希望以后/其他人更容易理解。
但只有在花了一些时间对文档进行排序之后,我才设法在正确的对象上监听正确的事件。因此,在这里分享我的工作示例,希望可以将其他人从繁琐的过程中拯救出来。
// make sure that Service Workers are supported.
if (navigator.serviceWorker) {
navigator.serviceWorker.register('/sw.js')
.then(function (registration) {
console.log("ServiceWorker registered");
// updatefound event is fired if sw.js changed
registration.onupdatefound = swUpdated;
}).catch(function (e) {
console.log("Failed to register ServiceWorker", e);
})
}
function swUpdated(e) {
console.log('swUpdated');
// get the SW which being installed
var sw = e.target.installing;
// listen for installation stage changes
sw.onstatechange = swInstallationStateChanged;
}
function swInstallationStateChanged(e) {
// get the SW which being installed
var sw = e.target;
console.log('swInstallationStateChanged: ' + sw.state);
if (sw.state == 'installed') {
// is any sw already installed? This function will run 'before' 'SW's activate' handler, so we are checking for any previous sw, not this one.
if (navigator.serviceWorker.controller) {
console.log('Content has updated!');
} else {
console.log('Content is now available offline!');
}
}
if (sw.state == 'activated') {
// new|updated SW is now activated.
console.log('SW is activated!');
}
}
于 2017-01-29T00:16:41.483 回答