【问题标题】:React Service worker: Load new content without forcing user to close the tabReact Service Worker:加载新内容而不强制用户关闭选项卡
【发布时间】:2020-10-14 11:09:41
【问题描述】:

我正在努力在 react 中实现 service worker 概念,我已经添加了链接 making-a-progressive-web-app 中建议的所有配置,但这里的问题是显示新内容(当网络从离线变为在线时) ,我必须向用户显示“关闭现有选项卡后新内容可用”之类的消息。所以在这里我们强制用户关闭页面以显示新内容。甚至刷新选项在这里也不起作用。

查看下面的方法 - (这是我们使用create-react-app构建react app时创建的方法,该方法可以在react-app/service-worker.js中找到)

function registerValidSW(swUrl, config) {
  navigator.serviceWorker
    .register(swUrl)
    .then(registration => {
      registration.onupdatefound = () => {
        const installingWorker = registration.installing;
        if (installingWorker == null) {
          return;
        }
        installingWorker.onstatechange = () => {
          if (installingWorker.state === 'installed') {
            if (navigator.serviceWorker.controller) {
              // At this point, the updated precached content has been fetched,
              // but the previous service worker will still serve the older
              // content until all client tabs are closed.
              console.log(
                'New content is available and will be used when all ' +
                  'tabs for this page are closed. See'
              );

              // Execute callback
              if (config && config.onUpdate) {
                config.onUpdate(registration);
              }
            } 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.');

              // Execute callback
              if (config && config.onSuccess) {
                config.onSuccess(registration);
              }
            }
          }
        };
      };
    })
    .catch(error => {
      console.error('Error during service worker registration:', error);
    });
}

你可以清楚地看到控制台

新内容可用,将在此页面的所有选项卡关闭时使用。

实现这一目标的最佳方法是什么?所以只有刷新页面,我们才能更新之前存储的缓存。

【问题讨论】:

  • 就个人而言,in my app,我选择在不询问用户的情况下刷新应用程序。但是location.reload() 无论如何都应该完成这项工作。
  • 你搞定了吗?我也面临同样的问题。
  • location.reload() 不起作用。那只会刷新页面,不会刷新 service worker。

标签: javascript reactjs create-react-app service-worker web-worker


【解决方案1】:

您好,我在使用 PWA 时遇到了同样的问题,您可以在您注册 service-worker 的地方使用以下代码

serviceWorker.register({
    onUpdate: registration => {
    alert('New version available!  Ready to update?');
    window.location.reload();
      if (registration && registration.waiting) {
        registration.waiting.postMessage({ type: 'SKIP_WAITING' });
      }
    }
  });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-23
    • 2017-06-09
    • 2017-12-08
    • 1970-01-01
    • 2021-11-20
    • 1970-01-01
    相关资源
    最近更新 更多