'Modifying responses in service worker requests to be an image

Hello and thank you in advance.

My question is about responding to a network request using ServiceWorker. I am able to handle it in case of a text or html, but when I am trying to deal with an image I am failing, here is the code I have:

self.addEventListener('fetch', function(event){
event.respondWith(
    fetch(event.request).then(function(response){
        if(response.status === 404){
            return new Response('The page wasn\'t found');
        }
        return response;  
     }).catch(function(){
            return new Response('The network is totally failed');
     })
    );
 });

The snippet above is working when dealing with text and html but when I am trying with an image it brings a totally black screen. Here what I used but it didn't work.

self.addEventListener('fetch', function(event){
event.respondWith(
    fetch(event.request).then(function(response){
        if(response.status === 404){
            return new Response('/imgs/sunset.gif', {headers:{'Content-Type':'image/gif'}});
        }
        return response;  
     }).catch(function(){
            return new Response('The network is totally failed');
     })
    );
 });

Hopefully you can help me in knowing what I am missing. thanks.



Solution 1:[1]

You need to replace your line :

return new Response('/imgs/sunset.gif', {headers:{'Content-Type':'image/gif'}});

By :

return new Response("<img src='/imgs/sunset.gif'/>", {headers:{'Content-Type': 'text/html'}});

You want to display a gif in your page, so you have to add a html content with and tell its source src.

Or easier solution you can only write this :

return fetch('/imgs/sunset.gif');

Solution 2:[2]

You can use fetch to get image or gif from files like below.

self.addEventListener('fetch', function(event) {
  event.respondWith(
    fetch(event.request).then(function(response) {
      if (response.status === 404) {           
        return fetch("/path/to/404error.gif");
      }
      return response;
    }).catch(function() {
      return new Response("Uh oh, that totally failed!");
    })
  );
});

Solution 3:[3]

I was looking for a similar solution and the following works:

self.addEventListener('fetch', function(event) {
  event.respondWith(
    fetch(event.request).then(function(response) {
      if (response.status === 404) {
        return fetch('/imgs/sunset.gif');
      }
      return response;
    }).catch(function() {
      return new Response("Uh oh, that totally failed!");
    })
  );
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Yunus
Solution 3 nwaweru