【发布时间】:2020-02-05 17:31:47
【问题描述】:
我想要实现的是当我的 React 网页有可用更新时向用户推送通知的能力,我正在尝试通过 serviceWorkers 来实现。
我面临的挑战是让 serviceWorkerRegistration 接口的安装属性不返回 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)
})
【问题讨论】:
标签: javascript reactjs typescript service-worker