【发布时间】:2020-10-14 11:09:41
【问题描述】:
我正在努力在 react 中实现 service worker 概念,我已经添加了链接 making-a-progressive-web-app 中建议的所有配置,但这里的问题是显示新内容(当网络从离线变为在线时) ,我必须向用户显示“关闭现有选项卡后新内容可用”之类的消息。所以在这里我们强制用户关闭页面以显示新内容。甚至刷新选项在这里也不起作用。
查看下面的方法 - (这是我们使用create-react-app构建react app时创建的方法,该方法可以在react-app/service-worker.js中找到)
function registerValidSW(swUrl, config) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
if (installingWorker == null) {
return;
}
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the updated precached content has been fetched,
// but the previous service worker will still serve the older
// content until all client tabs are closed.
console.log(
'New content is available and will be used when all ' +
'tabs for this page are closed. See'
);
// Execute callback
if (config && config.onUpdate) {
config.onUpdate(registration);
}
} 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 cached for offline use.');
// Execute callback
if (config && config.onSuccess) {
config.onSuccess(registration);
}
}
}
};
};
})
.catch(error => {
console.error('Error during service worker registration:', error);
});
}
你可以清楚地看到控制台
新内容可用,将在此页面的所有选项卡关闭时使用。
实现这一目标的最佳方法是什么?所以只有刷新页面,我们才能更新之前存储的缓存。
【问题讨论】:
-
就个人而言,in my app,我选择在不询问用户的情况下刷新应用程序。但是
location.reload()无论如何都应该完成这项工作。 -
你搞定了吗?我也面临同样的问题。
-
location.reload()不起作用。那只会刷新页面,不会刷新 service worker。
标签: javascript reactjs create-react-app service-worker web-worker