簡體   English   中英

ServiceWorker 更新循環 - 創建反應應用程序

[英]ServiceWorker Update loop - Create react app

我正在嘗試為用戶實現一個彈出窗口,告訴他們有可用的更新。

我正在使用 Create React App,它是默認配置。 當它發現更新時,我正在調度一個動作,如下所示:

索引.js

serviceWorker.register({
    onSuccess: () => store.dispatch({ type: SW_UPDATE_FINISHED }),
    onUpdate: reg => store.dispatch({ type: SW_UPDATE, payload: reg })
});

我有一個小組件應該負責顯示消息和觸發更新:

const SwUpdate = () => {
  const swUpdate = useSelector(state => state.app.swUpdate);
  const swReg = useSelector(state => state.app.swReg);
  const dispatch = useDispatch();

  const updateSw = () => {
    const swWaiting = swReg && swReg.waiting;
    if (swWaiting) {
      swWaiting.postMessage({ type: 'SKIP_WAITING' });
      dispatch({ type: SW_UPDATE_FINISHED });
      window.location.reload();
    } else {
      dispatch({ type: SW_UPDATE_FINISHED });
    }
  }

  return (
    <Snackbar
      open={swUpdate}
      color="primary"
      message="New version available! 🎊"
      action={
        <Button color="primary" size="small" onClick={updateSw}>
          UPDATE
        </Button>
      }
    />
  )
}

export default SwUpdate;

它做我認為應該做的事情,重新加載頁面......但是......

再次......你有一個更新! 每次從檢查員手動執行都是相同的故事,我得到一個新的軟件,但我不明白為什么會發生這種情況

在此處輸入圖片說明

我似乎找不到其他人發生這種情況的例子,我擔心是我做錯了什么,或者 CRA 服務工作者有問題,我只將回調添加到寄存器的配置參數中並對其進行管理特定組件。

編輯:添加服務工作者代碼

我有來自 Create react App 的serviceWorker.js AS IS:

// This optional code is used to register a service worker.
// register() is not called by default.

// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on subsequent visits to a page, after all the
// existing tabs open on the page have been closed, since previously cached
// resources are updated in the background.

const isLocalhost = Boolean(
  window.location.hostname === 'localhost' ||
    // [::1] is the IPv6 localhost address.
    window.location.hostname === '[::1]' ||
    // 127.0.0.0/8 are considered localhost for IPv4.
    window.location.hostname.match(
      /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
    )
);

export function register(config) {
  if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
    // The URL constructor is available in all browsers that support SW.
    const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
    if (publicUrl.origin !== window.location.origin) {
      // Our service worker won't work if PUBLIC_URL is on a different origin
      // from what our page is served on. This might happen if a CDN is used to
      // serve assets;
      return;
    }

    window.addEventListener('load', () => {
      const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;

      if (isLocalhost) {
        // This is running on localhost. Let's check if a service worker still exists or not.
        checkValidServiceWorker(swUrl, config);

        // Add some additional logging to localhost, pointing developers to the
        // service worker/PWA documentation.
        navigator.serviceWorker.ready.then(() => {
          console.log(
            'This web app is being served cache-first by a service ' +
              'worker. To learn more, visit <LINK>'
          );
        });
      } else {
        // Is not localhost. Just register service worker
        registerValidSW(swUrl, config);
      }
    });
  }
}

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);
    });
}

function checkValidServiceWorker(swUrl, config) {
  // Check if the service worker can be found. If it can't reload the page.
  fetch(swUrl, {
    headers: { 'Service-Worker': 'script' }
  })
    .then(response => {
      // Ensure service worker exists, and that we really are getting a JS file.
      const contentType = response.headers.get('content-type');
      if (
        response.status === 404 ||
        (contentType != null && contentType.indexOf('javascript') === -1)
      ) {
        // No service worker found. Probably a different app. Reload the page.
        navigator.serviceWorker.ready.then(registration => {
          registration.unregister().then(() => {
            window.location.reload();
          });
        });
      } else {
        // Service worker found. Proceed as normal.
        registerValidSW(swUrl, config);
      }
    })
    .catch(() => {
      console.log(
        'No internet connection found. App is running in offline mode.'
      );
    });
}

export function unregister() {
  if ('serviceWorker' in navigator) {
    navigator.serviceWorker.ready.then(registration => {
      registration.unregister();
    });
  }
}

我知道他們使用 Workbox 進行配置,我正在通過運行npm run buildserve -s build並重新加載來測試所有這些。

另外,這是在構建應用程序時由 Workbox 的 Create react 應用程序配置生成的 service-worker 文件:

/**
 * Welcome to your Workbox-powered service worker!
 *
 * You'll need to register this file in your web app and you should
 * disable HTTP caching for this file too.
 *
 * The rest of the code is auto-generated. Please don't update this file
 * directly; instead, make changes to your Workbox build configuration
 * and re-run your build process.
 */

importScripts("https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-sw.js");

importScripts(
  "/precache-manifest.a4724df64b745797c25a9173550ba2d3.js"
);

self.addEventListener('message', (event) => {
  if (event.data && event.data.type === 'SKIP_WAITING') {
    self.skipWaiting();
  }
});

workbox.core.clientsClaim();

/**
 * The workboxSW.precacheAndRoute() method efficiently caches and responds to
 * requests for URLs in the manifest.
 */
self.__precacheManifest = [].concat(self.__precacheManifest || []);
workbox.precaching.precacheAndRoute(self.__precacheManifest, {});

workbox.routing.registerNavigationRoute(workbox.precaching.getCacheKeyForURL("/index.html"), {
  
  blacklist: [/^\/_/,/\/[^/?]+\.[^/]+$/],
});

顯然,Firebase 消息傳遞需要另一個 service-worker 來發送推送通知,每次都會觸發更新。

老實說,我沒有在最初的問題中提到它,因為我認為它與我的問題沒有任何關系。

我最終將 FCM 設置為使用我的 service worker 而不是擁有它,並且一切都開始正常工作:)

我不能說更多,因為我不是 100% 確定問題到底是什么,可能 FCM serviceworker 沒有更新自己,而是讓另一個人每次都嘗試更新自己? 服務人員很奇怪

我遇到了完全相同的問題,每當更新彈出窗口時都會顯示更新頁面,而新的 Service Worker 將處於等待狀態。 我相信問題是來自復選框Update on Reload (在應用程序選項卡上)被勾選。 一旦我關閉它,一切似乎都按預期工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM