Search code examples
javascriptcachingfetch-apiservice-worker

service worker not returning to fallback page


service worker not returning to fallback page (/offline.html) the issue is with only server (firebase hosting) but with the local host it's working and returning to '/offline.html' page. do anyone know what is the reason and how to solve this?

No Errors but I'm keep getting this warning from the console:

The FetchEvent for "<URL>" resulted in a network error response: a redirected response was used for a request whose redirect mode is not "follow".

this is my code:

self.addEventListener("fetch", (evt) => {
  handleFetchIvent(evt);
});

function handleFetchIvent(evt) {
  if (evt.request.redirect == "follow") {
    console.log(evt.request.redirect);
    evt.respondWith(
      caches
        .match(evt.request)
        .then((cacheRes) => {
          return (
            cacheRes ||
            fetch(evt.request.url).then(
              async (fetchRes) => {
                // got a response from server

                const cache = await caches.open(dynamicCacheName);
                cache.put(evt.request.url, fetchRes.clone());

                // check cached items size
                limitCacheSize(dynamicCacheName, 5);
                return fetchRes;
              },
              (error) => {
                // network error
                return cache.match("/offline.html");
              }
            )
          );
        })
        .catch(() => {
          return caches.match("/offline.html");
        })
    );
  } // Change the redirect mode
  else if (
    evt.request.redirect == "manual" ||
    evt.request.redirect == "error"
  ) {
    const modRequest = new Request(evt.request, {
      redirect: "follow",
    });

    console.log(modRequest.redirect);
    evt.respondWith(
      caches
        .match(modRequest)
        .then((cacheRes) => {
          return (
            cacheRes ||
            fetch(modRequest.url).then(
              async (fetchRes) => {
                // got a response from server

                const cache = await caches.open(dynamicCacheName);
                cache.put(modRequest.url, fetchRes.clone());

                // check cached items size
                limitCacheSize(dynamicCacheName, 5);
                return fetchRes;
              },
              (error) => {
                // network error
                return cache.match("/offline.html");
              }
            )
          );
        })
        .catch(() => {
          return caches.match("/offline.html");
        })
    );
  }
}

Solution

  • it's quite simple as water. all you have to do is replace https://www.example.com/offline with /offline.html. that's it problem solved.