1
votes

I am trying to setup a service worker so that my web-app can fully work offline. When I inspect the cache for static-v2 all of my assets that I want are there.

When I make a request and am online my SW is correctly doing the fetch and not falling into my catch statement.

However, when I am offline and I fall through to my cache the correct response is logged with the status of 200 but I get the chrome 'no internet' error.

Another interesting point is even when I comment out the line where I return the cache response and just return the hard coded response I still get the 'no internet' error.

Any help in figuring out why my service worker isn't working as expected would be greatly appreciated.

const CACHENAME = `static-v2`;

self.addEventListener('install', function(event) {
  event.waitUntil(
    caches.open(CACHENAME).then(function(cache) {
      return cache
        .addAll([
          // your list of cache keys to store in cache
          'bundle.js',
          'index.html',
          'manifest.json',
          // etc.
        ])
        .then(() => {
          return self.skipWaiting();
        });
    }),
  );
});

self.onactivate = (evt) => {
  console.log(`on activate - ${CACHENAME}`);

  evt.waitUntil(
    caches.keys().then((cacheNames) => {
      const deleteOldCaches = cacheNames.map((cacheName) => {
        console.log(cacheName);

        if (cacheName != CACHENAME) {
          return caches.delete(cacheName);
        }

        return Promise.resolve();
      });

      return Promise.all(deleteOldCaches);
    }),
  );

  self.clients.claim();
};

self.onfetch = (evt) => {
  evt.waitUntil(
    fetch(evt.request).catch((err) => {
      caches.match(evt.request).then((response) => {
        console.log(evt.request.url, response);

        if (response) return response;

        return new Response('<div><h2>Uh oh that did not work</h2></div>', {
          headers: {
            'Content-type': 'text/html',
          },
        });
      });
    }),
  );

  console.log(`on fetch - ${CACHENAME}`);
};

I am hosting all of my assets (inc SW) using http-server (https://www.npmjs.com/package/http-server)

1

1 Answers

0
votes

It's a simple mistake.

In your fetch event handler, you should NOT call evt.waitUntil. You should call evt.respondWith.