Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Seeing if a request succeeds from within a service worker

I have the following code in my service worker:

self.addEventListener('fetch', function (event) {
  var fetchPromise = fetch(event.request);

  fetchPromise.then(function () {
    // do something here
  });

  event.respondWith(fetchPromise);
});

However, it's doing some weird stuff in the dev console and seems to be making the script load asynchronously instead of synchronously (which in this context is bad).

Is there any way to listen for when a request is completed without calling fetch(event.request) manually?

For example:

// This doesn't work
self.addEventListener('fetch', function (event) {
  event.request.then(function () {
    // do something here
  });
});
like image 542
callumacrae Avatar asked Oct 15 '15 10:10

callumacrae


People also ask

How do I find out if a service worker is running?

You can look at Service Worker Detector, a Chrome extension that detects if a website registers a Service Worker by reading the navigator. serviceWorker.

Is service worker intercepted?

Service Workers are a special type of Web Worker with the ability to intercept, modify, and respond to all network requests using the Fetch API. Service Workers can access the Cache API, and asynchronous client-side data stores, such as IndexedDB , to store resources.

What is an example of a service worker?

Examples of personal service positions include: medical assistants and other healthcare support positions, hairdressers, ushers, and transportation attendants. Examples of cleaning service positions include: cleaners, janitors, and porters.

Can service workers access cache?

Using a Service worker you can easily set an app up to use cached assets first, thus providing a default experience even when offline, before then getting more data from the network (commonly known as Offline First).


1 Answers

If you want to ensure that your entire series of actions are performed before the response is returned to the page, you should respond with the entire promise chain, not just the initial promise returned by fetch.

self.addEventListener('fetch', function(event) {
  event.respondWith(fetch(event.request).then(function(response) {
    // The fetch() is complete and response is available now.
    // response.ok will be true if the HTTP response code is 2xx
    // Make sure you return response at the end!
    return response;
  }).catch(function(error) {
    // This will be triggered if the initial fetch() fails,
    // e.g. due to network connectivity. Or if you throw an exception
    // elsewhere in your promise chain.
    return error;
  }));
});
like image 75
Jeff Posnick Avatar answered Sep 24 '22 03:09

Jeff Posnick