service-workerworkboxrequest-cancelling

How to cancel/modify/alter/replace a request in respondWith?


I'm using a workbox and trying to cache requests something like this:

this.serviceWorker.addEventListener('fetch', (event) => {
const request = event.request;
event.respondWith(
      caches.open('cache name')
         .then(cache => cache.match(request))
         .then(async (cachedResponse) => {
            // todo something

How Can I cancel event.request and send my custom request? Thanks for any helping.


Solution

  • You may alter or completely change the out-going request like so:

    this.serviceWorker.addEventListener('fetch', (event) => {
      const request = event.request;
      return event.respondWith(
        caches.open('cache name')
          .then(cache => cache.match(request))
          .then(async (cachedResponse) => {
            // create a new request, fetchi it, and return the result
            return fetch(new Request(request.url ....))
           })
    
    

    Pay attention to the return statement I added to the third line of code :)

    More info about constructing the new request: https://stackoverflow.com/a/35421858/5038943