Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ServiceWorker not receiving fetch requests

I am installing a service worker for the first time, and following the tutorial at: https://developers.google.com/web/fundamentals/getting-started/primers/service-workers

My service worker behaves as expected when installing and updating, but fetch requests are not triggered as expected.

var CACHE_NAME = 'test-cache-v1'
var urlsToCache = [
  '/',
  '/public/scripts/app.js'
]

self.addEventListener('install', function (event) {
  console.log('Installing new service worker', event)
  // Perform install steps
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then(function (cache) {
        return cache.addAll(urlsToCache)
      })
      .catch(err => console.log('Error Caching', err))
)
})

self.addEventListener('fetch', function (event) {
  console.log('Fetch req', event)
  event.respondWith(
    caches.match(event.request)
      .then(function (response) {
        console.log('Cache hit', response)
        // Cache hit - return response
        if (response) {
          return response
        }
        return fetch(event.request)
        .catch(e => console.log('Error matching cache', e))
      }
    )
  )
})

I see 'Installing new service worker' outputted to the console when expected, but not 'Fetch req'. I am using Chrome devtools and have accessed the "Inspect" option next to the ServiceWorker under the Application tab.

like image 551
David Jay Avatar asked Feb 20 '17 19:02

David Jay


1 Answers

If you listen for the activate event, and add in a call to clients.claim() inside that event, then your newly active service worker will take control over existing web pages in its scope, including the page that registered it. There's more information in this article on the service worker lifecycle. The following code is sufficient:

self.addEventListener('activate', () => self.clients.claim());

If you don't call clients.claim(), then the service worker will activate, but not control any of the currently open pages. It won't be until you navigate to the next page under its scope (or reload a current page) that the service worker will take control, and start intercepting network requests via its fetch handler.

like image 136
Jeff Posnick Avatar answered Oct 16 '22 14:10

Jeff Posnick