gpt4 book ai didi

reactjs - React & Service Worker - 缓存内容 - 通知用户

转载 作者:行者123 更新时间:2023-12-03 13:45:46 26 4
gpt4 key购买 nike

我有一个关于 service-workersreactjs 的问题。

建议是通知用户有关缓存的内容或何时有新内容可用,以便用户了解缓存的内容。

我现在的问题是,我如何通知用户?

当我使用create-react-app时,在registerServiceWorker.js中有这样的代码,其中写着:

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.

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);
});
}

但实际上在这个脚本上,我当然无权访问文档,因为服务工作线程远离脚本工作。我如何在 react 组件中处理这个问题?

其他人如何处理此问题并通知用户?

最佳答案

您的问题中包含的代码在window客户端的上下文中运行。您可以完全控制显示您想要的任何 UI 元素。请随意修改这些 console.log() 语句并显示一些内容。

(有单独的代码在服务工作人员的上下文中运行,并且您是正确的,该代码无法访问 DOM。但这不是您要询问的代码。)

关于reactjs - React & Service Worker - 缓存内容 - 通知用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47881734/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com