2
votes

I have this fetch function in my service worker and i try to respond with a different image when the pwa is offline. The fetch function inside the catch throws: Uncaught (in promise) TypeError: Failed to fetch.

self.addEventListener('fetch', (e) => {
  if (e.request.method === 'GET') {
    e.respondWith(
      caches.match(e.request).then((cachedResponse) => {
        return cachedResponse || fetch(e.request.url)
          .then((res) => {
            return res;
          }).catch(() => {
             //if it is a image then
            let url1 = e.request.url.replace(".jpg", "_mini.jpg");
            return fetch(url1);
            /* Or like this
            caches.match(url1).then((cResp) => {
            return cResp;
            })
           */
          })

      })
    )
  }
});

Is it not possible to catch an error when you are offline and respond with a "mini" alternativ image or what do i do wrong?

1
please define "it does not work". does it give an error? produce the incorrect image? show a blank page? crash the program with no error? cause the page to load infinitely? "it does not work" is the least possible amount of useful details to diagnose a problem in this code - Klaycon
The fetch(url1) fails with: Uncaught (in promise) TypeError: Failed to fetch. But like @Guerric P says, its because fetch does not work offline. - Samhamsam

1 Answers

1
votes

You are returning cachedResponse if it exists, that prevents your replacement logic from being reached. Try to remove cachedResponse ||.

This can be removed as well:

.then((res) => {
    return res;
})

Also, if you're offline the return fetch(url1); won't work because the fetch from a Service Worker won't trigger another FetchEvent recursively. So you have to return caches.match(url1) instead, implying it has been cached before.