首页 > 解决方案 > React Service Worker:加载新内容而不强制用户关闭选项卡

问题描述

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

检查以下方法 - (这是我们使用 create-react-app 构建 react 应用程序时创建的方法,该方法可以在 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);
    });
}

你可以清楚地看到控制台

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

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

标签: javascriptreactjscreate-react-appservice-workerweb-worker

解决方案


推荐阅读