Service Worker: Error Caught (in Promise) TypeError: Request scheme 'data' is unsupported

1.8k Views Asked by At

What happens is on the first load of the website fetching and caching does not encounter any problem. But, on refresh (normal reload) Fetch event encounters the problem and shows this on the console log.

Uncaught (in promise) TypeError: Request scheme 'data' is unsupported at self.addEventListener.e.respondWith.fetch.then.caches.open.then.cache

I realized that on reload it fetches a format data:[<mediatype>][;base64],<data>which causes the error in the console log.

// Call Fetch Event
self.addEventListener('fetch', e => {
  console.log('Service Worker: Fetching');
  e.respondWith(
    fetch(e.request)
      .then(res => {
        // Make copy/clone of response
        const resClone = res.clone();
        // Open cahce
        caches.open(cacheName).then(cache => {
          // Add response to cache
          cache.put(e.request, resClone);
        });
        return res;
      })
      .catch(err => caches.match(e.request).then(res => res))
  );
});

I want to avoid this error but I don't know how.

1

There are 1 best solutions below

4
On

A good practice is to open the cache before sending the fetch request so it ensures your cache exists. And you can fallback to your cache response if network fails. The following code will update your cache:

e.respondWith(
  caches.open(cacheName).then(cache => {
    cache.match(e.request).then(cacheResponse => {
      const networkFetch = fetch(e.request).then(networkResponse => {
        cache.put(e.request, networkResponse.clone());
        return networkResponse
      });

      return cacheResponse || networkFetch;
    });
  }).catch(error => {
    console.log('error in cache open: ', error)
  })
)