Catch request in service worker and respond with different image url

Viewed 370

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 Answers

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.

Related