我们的应用程序是一个聚合物2单页应用程序,我们有一些自定义的构建步骤,以生成资源的版本文件(Gulp)。一切运行良好,但我们需要实现应用程序的安全刷新。我们要做的是,将最新安装的git提交保存在一个与应用程序一起服务的文件中,并按间隔提取该文件,并提醒用户有新版本可用,并要求他们单击按钮刷新应用程序。
问题是,我们使用预缓存的服务工作者作为默认的聚合物构建提供。这意味着,当我们执行location.reload()时,实际上是从服务工作者而不是从服务器获得内容(index.html)。
因此,问题是:如何强制服务工作者失效并强制进行新的服务刷新-worker.js和index.html?
发布于 2018-01-12 21:00:14
这里的准备代码,都描述了如何处理服务工作者;
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('sw.js').then(function(reg) {
// updatefound is fired if sw.js changes.
reg.onupdatefound = function() {
// The updatefound event implies that reg.installing is set; see
// https://w3c.github.io/ServiceWorker/#service-worker-registration-updatefound-event
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.');
// Need to hard refresh when new content is available
location.reload(true);
} 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);
});
}https://stackoverflow.com/questions/48233171
复制相似问题