0

I need some help here. I'm currently using Chrome 86, trying out a tutorial with JS Service Workers. (This tutorial) to be specific. However, it doesn't seem to work. Upon looking at chrome://serviceworker-internals, I found that my service worker doesn't appear to have a fetch handler. However, this shouldn't be the case since I have added a fetch event listener on my service worker script.

Below is the script.

// Service worker code
'use strict';

var cacheVersion = 1;
var currentCache = {
  offline: 'offline-cache' + cacheVersion
};

const offlineURL = '/offline.html';

self.addEventListener('install', event => {
  event.waitUntil(
    caches.open(currentCache.offline).then(c => {
      return c.addAll([
        /* Additional resources for offline page, */
        
        /* Don't touch this */
        offlineURL
      ]);
    })
  );
});

self.addEventListener('fetch', event => { // This seems to not be detected
  // request.mode = navigate isn't supported in all browsers
  // so include a check for Accept: text/html header.
  if (event.request.mode === 'navigate' || (event.request.method === 'GET' && event.request.headers.get('accept').includes('text/html'))) {
        event.respondWith(
          fetch(event.request.url).catch(error => {
              // Return the offline page
              return caches.match(offlineUrl);
          })
    );
  }
  else{
        // Respond with everything else if we can
        event.respondWith(caches.match(event.request)
                        .then(function (response) {
                        return response || fetch(event.request);
                    })
            );
      }
});

I've commented the portion that seems to be buggy.

If anyone could help, that would be appreciated!

Thanks.

Frank
  • 81
  • 1
  • 2
  • 11
  • 1
    https://stackoverflow.com/questions/34147562/service-worker-is-caching-files-but-fetch-event-is-never-fired – AM Douglas Oct 22 '20 at 01:58
  • forgot to mention, my sw.js is in the root directory.... Thx for the help though. Could it be a problem with the `event.request` handling? – Frank Oct 22 '20 at 16:16
  • try this https://stackoverflow.com/a/64314859/1289713 – Vimal Patel Oct 23 '20 at 17:36
  • my `event.respondWith` function is only called after the if statement, could it be the if statement doesn't hold true in Chrome? (like I mentioned, the `event.request`) part – Frank Oct 24 '20 at 02:39

0 Answers0