我有一个使用 Aurelia 构建并使用 Webpack 编译的 PWA,使用生成sw.js
服务工作者文件的 Workbox 插件。我正在尝试提供“新版本可用”用户通知,以便用户在单击应用程序中的链接时可以激活新版本。
我在后台成功下载并安装了新版本,甚至检测到新版本已经准备好。但是,当我尝试调用该skipWaiting()
方法以使用新版本强制刷新页面时,它会失败,因为显然我没有正确的范围或对象。
主要问题可能是我无法编辑实际的 sw.js,因为它是自动生成的。这些示例都建议使用self.skipWaiting();
,但我不知道如何访问该对象。
webpack.config.js
new WorkboxPlugin({
globDirectory: './dist',
globPatterns: ['**/*.{html,js,css,woff,woff2,ttf,svg,eot,jpg}'],
swDest: './dist/sw.js',
clientsClaim: true,
skipWaiting: false, // because I want to notify the user and wait for response
}),
索引.ejs
<script>
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js')
.then(reg => {
// make the registration available globally, for access within app
window.myServiceWorkerReg = reg;
// Check for update on loading the app (is this necessary?)
return reg.update();
})
.catch(console.error);
}
</script>
应用程序.js
activate() {
// listener for service worker update
this.swReg = window.myServiceWorkerReg;
console.warn('[app.js] ACTIVATE.', this.swReg);
this.swReg.addEventListener('updatefound', () => {
// updated service worker found in reg.installing!
console.warn('[app.js] UPDATE FOUND.', this.swReg);
const newWorker = this.swReg.installing;
newWorker.addEventListener('statechange', () => {
// has the service worker state changed?
console.warn('[app.js] STATE HAS CHANGED.', newWorker, newWorker.state);
if (newWorker.state === 'installed') {
// New service worker ready.
// Notify user; callback for user request to load new app
myUserMessage({ clickToActivate: () => {
// reload fresh copy (do not cache)
console.warn('[app.js] Post Action: skipWaiting.');
// this.swReg.postMessage({ action: 'skipWaiting' });
// THIS IS THE LINE THAT FAILS
this.swReg.skipWaiting();
}});
}
});
});
}
除了最后一行 ( this.swReg.skipWaiting();
) 外,一切正常。有没有其他人使用过 webpack+workbox 插件并且由于用户交互而导致 skipWaiting 发生?