我有一个关于service workers和reactjs的问题。
建议告知用户缓存的内容或何时可用新内容,以便用户了解缓存的内容。
我现在的问题是,我如何通知用户?
当我使用create-react-app时,在registerServiceWorker.js中有这样的代码:
此时,旧内容将被清除,新内容将被添加到缓存中。现在是显示“新内容可用;请刷新”的最佳时机。在你的网络应用中留言。
function registerValidSW(swUrl) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
installingWorker.onstatechange = () => {
if (installingWorker.state === '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 your web app.
console.log('New content is available; please refresh.');
} 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.');
}
}
};
};
})
.catch(error => {
console.error('Error during service worker registration:', error);
});
}但是实际上,在这个脚本上,当然,我不能访问document,因为服务工作者远离脚本工作。我如何在一个反应组件中处理这个问题?
其他人如何处理这个问题并通知用户?
发布于 2017-12-19 16:18:44
问题中包含的代码运行在window客户端的上下文中。您可以完全控制显示任何您想要的UI元素。可以随意修改这些console.log()语句并显示一些内容。
(在服务工作人员的上下文中运行的代码是独立的,您正确地知道,该代码没有访问DOM的权限。但这不是你要问的代码。)
https://stackoverflow.com/questions/47881734
复制相似问题