2

I have a ServiceWorker that intercepts Fetch Requests. Sometimes, the fetch request is doomed to fail, so the ServiceWorker should cancel it before it even hits the network.

My code looks like:

async function onFetch(event) {
  const { request } = event;

  const result = handleRequest(request)
    .then(someStuff)
    .catch((err) => {
      const ctrl = new AbortController();
      ctrl.abort('request is doomed');

      const cancellation = fetch(request, { signal: ctrl.signal });
      // cancellation is correctly an AbortError DOMException

      // event.respondWith(cancellation); // results in net::ERR_FAILED
      return cancellation;
    });
  
  return event.waitUntil(result);
}

A quick experiment without a service worker suggests this should work:

const ctrl = new AbortController();
ctrl.abort('request is doomed');

fetch('http://localhost', { signal: ctrl: signal });

In the above experiment, the request in DevTools Network panel is marked "cancelled" and no network request is made.

However, in the ServiceWorker, the request is not cancelled (the abort signal is ignored completely) and it goes out to the network.

Jakob Jingleheimer
  • 30,952
  • 27
  • 76
  • 126

0 Answers0