如何响应服务工作者中导航的获取事件?

How to respond to fetch event for a navigation in service worker?

我已经使用 Create-React-App 创建了一个 SPA(单页应用程序)。我向其中添加了一个服务工作者,以便在没有网络连接时可以加载 SPA。 Service Worker 成功缓存了所有资源,但在没有网络连接时无法响应。我已经尝试了很多东西,但就是无法让它为资产提供服务以获取离线功能。它给出以下错误消息:

Uncaught (in promise) TypeError: Failed to fetch

我的 service worker 注册成功,也成功缓存资产。服务工作者代码:

const thingsToCache = [
  'index.html',
  'static/js/1.cb2fedf5.chunk.js',
  'static/js/main.5e7fdc75.chunk.js',
  'static/js/runtime~main.229c360f.js',
  'static/css/main.ca6d346b.chunk.css',
  'static/media/roboto.18d44f79.ttf',
  'static/media/comfortaa.7d0400b7.ttf',
];

this.addEventListener('install', event => {
  event.waitUntil(
    caches.open('v1').then(cache => {
      return cache.addAll(thingsToCache);
    })
  );
});

this.addEventListener('fetch', event => {
  //respond to fetch requests here
  caches
    .match(event.request)
    .then(cachedRes => {
      if (cachedRes) {
        event.respondWith(cachedRes);
      } else {
        throw new Error('No match found in cache!');
      }
    })
    .catch(() => {
      return fetch(event.request);
    });
});

如果您需要资源,那么这里是link:

https://github.com/Twaha-Rahman/pwa-problem-assets

感谢大家的帮助!

您的 fetch 事件侦听器出错。您需要调用 event.respondWith 而不是 event.waitUntil 并且它必须位于顶层。请参阅下面的略微修改版本。

this.addEventListener('fetch', event => {
  event.respondWith(
    caches
      .match(event.request)
      .then(cachedRes => {
        if (cachedRes) {
          return cachedRes;
        } else {
          throw new Error('No match found in cache!');
        }
      })
      .catch(() => {
        return fetch(event.request);
      });
  )
});

更多详情:https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers