gpt4 book ai didi

javascript - 如何在开发环境中测试更新 Service Worker?

转载 作者:行者123 更新时间:2023-12-04 14:27:01 25 4
gpt4 key购买 nike

我想要实现的是当我的 React 网页有可用更新时向用户推送通知的能力,我正在尝试通过 serviceWorkers 这样做。

我面临的挑战是让 serviceWorkerRegistration 接口(interface)的安装属性不返回 null。我只想触发console.log('New content is available; please refresh.')
我对在 React 中使用 serviceWorkers 很陌生。有没有人知道如何在开发环境中测试 serviceWorkers 的更新功能?

  console.log('I am in registerValidSW!')
navigator.serviceWorker
.register(swUrl)
.then((registration) => {
console.log(registration)
registration.onupdatefound = () => {
const installingWorker = registration.installing //This returns null
if (installingWorker) {
console.log('installingServiceWorker!!!')
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)
})


最佳答案

@krish 根据新文档-> Service Worker 仅在生产环境中启用,例如npm run build 的输出。建议您不要在开发环境中启用离线优先 Service Worker,因为当使用以前缓存的 Assets 并且不包括您在本地所做的最新更改时,这可能会导致沮丧。请参阅此链接:- https://create-react-app.dev/docs/making-a-progressive-web-app/

关于javascript - 如何在开发环境中测试更新 Service Worker?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60081161/

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