我们的应用程序是Polymer 2单页面应用程序,我们有一些自定义构建步骤来生成资源的版本化文件(gulp-rev-all)。一切都运行良好,但我们需要实现应用程序的安全刷新。我们正在做的是我们将最新安装的git commit保存在与应用程序一起提供的文件中,我们会定期提取此文件并提醒用户有新版本可用并要求他们单击按钮刷新应用程序。
问题是我们正在使用具有预缓存的服务工作者作为默认的Polymer构建提供。这意味着当我们执行location.reload()时,我们实际上从服务工作者那里获取内容(index.html),而不是从服务器获取内容。
所以问题是:我们如何强制服务工作者无效并强制刷新service-worker.js和index.html?
答案 0 :(得分:0)
这里是准备好的代码,全部描述了如何处理服务工作者;
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);
});
}