【问题标题】:How do I test updating a service worker in a development environment?如何在开发环境中测试更新服务工作者?
【发布时间】: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


    【解决方案1】:

    @krish 根据新文档-> service worker 仅在生产环境中启用,例如npm run build 的输出。建议您不要在开发环境中启用离线优先服务工作者,因为当使用以前缓存的资产并且不包括您在本地所做的最新更改时,这可能会导致挫败感。参考这个链接:-https://create-react-app.dev/docs/making-a-progressive-web-app/

    【讨论】:

    • OP 并没有询问您是否应该在开发中启用服务人员,而是询问如果您不应该激活服务人员,如何在开发中测试服务人员
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多