Modifying responses in service worker requests to be an image

request and response object in javascript
service worker response object
javascript get response body
response data
javascript http response
response js
response object http
promise response object

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.

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');

Using Service Workers, Service worker syntax is more complex than that of AppCache, but the 200) { resolve(request.response); } else { reject(Error('Image didn\'t load here is the promise (see app.js lines 22-47), which is a modified version of  The service worker will only catch requests from clients under the service worker's scope. The max scope for a service worker is the location of the worker. If your service worker is active on a client being served with the Service-Worker-Allowed header, you can specify a list of max scopes for that worker.

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!");
    })
  );
});

FetchEvent.respondWith(), For example, if an <img> initiates the request, the response body needs to be image data. respondWith() , the Response.url value will be propagated to the intercepted This means, for example, if a service worker intercepts a stylesheet or For most types of network request this change has no impact  The Service Worker API comes with a Cache interface, that lets you create stores of responses keyed by request. While this interface was intended for service workers it is actually exposed on the window, and can be accessed from anywhere in your scripts. The entry point is caches. You are responsible for implementing how your script (service

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!");
    })
  );
});

Chapter 4. Intercepting network requests, Instead of the user making a request to the server, the Service Worker intercepts the 3 Try to fetch an image of a unicorn and respond with it instead. Intercepting HTTP requests, editing HTTP responses, and crafting your own responses  There's overhead involved in starting up a service worker if it's not already running, and there's also overhead in passing the response from the service worker to the client that made the request. If your service worker doesn't contain a fetch handler at all, some browsers will make note of that and not bother starting up the service worker

Handling broken images with the service worker, With the service worker API, making icons, text, images and fonts display offline At the very least, if a request gets to the server we are supposed to get a response, In the event that you are trying to save a PUT request, you can just change  If your web app might request an arbitrary number of unique resource URLs, then using a library like sw-toolbox which provides cache-expiration is recommended. Live Demo. The following demo illustrates the service worker's runtime caching by loading images in response to clicking the button below.

How to Handle POST/PUT requests in offline applications using , Adding a service worker to your web app can offer significant History API and in-place DOM modifications, tend to avoid navigation requests when scripts, images, or styles—it's the HTML in the navigation response that's  Service workers essentially act as proxy servers that sit between web applications, the browser, and the network (when available). They are intended, among other things, to enable the creation of effective offline experiences, intercept network requests and take appropriate action based on whether the network is available, and update assets residing on the server. They will also allow access

High-performance service worker loading, This code uses the workbox-window package to register a service worker and react if it gets stuck in Use event, request, and url to figure out how to respond. Service Worker Get Headers Being able to see headers information on every request can be very useful in your browser's network console. But it could sometimes be interesting to access these headers informations from the page, in JavaScript.

Comments
  • I think what's actually happening is that the content of the response is the text "/imgs/sunset.gif" and not the actual gif. You will need to create a Blob with the image data and pass that as the first argument to the Response constructor.