W3cubDocs

/DOM

ServiceWorkerGlobalScope.onfetch

The onfetch property of the ServiceWorkerGlobalScope interface is an event handler fired whenever a fetch event occurs (usually when the ServiceWorkerGlobalScope.fetch method is called.)

Syntax

ServiceWorkerGlobalScope.onfetch = function(FetchEvent) { ... }

Example

This code snippet is from the service worker fetch sample (see prefetch example live.) The ServiceWorkerGlobalScope.onfetch event handler listens for the fetch event. When fired, the code returns a promise that resolves to the first matching request in the Cache object. If no match is found, the code fetches a response from the network.

The code also handles exceptions thrown from the ServiceWorkerGlobalScope.fetch operation. Note that an HTTP error response (e.g., 404) will not trigger an exception. It will return a normal response object that has the appropriate error code set.

self.addEventListener('fetch', function(event) {
  console.log('Handling fetch event for', event.request.url);

  event.respondWith(
    caches.match(event.request).then(function(response) {
      if (response) {
        console.log('Found response in cache:', response);

        return response;
      }
      console.log('No response found in cache. About to fetch from network...');

      return fetch(event.request).then(function(response) {
        console.log('Response from network is:', response);

        return response;
      }).catch(function(error) {
        console.error('Fetching failed:', error);

        throw error;
      });
    })
  );
});

Specifications

Specification Status Comment
Service Workers
The definition of 'Event Handlers' in that specification.
Working Draft Initial definition

Browser compatibilityUpdate compatibility data on GitHub

Desktop
Chrome Edge Firefox Internet Explorer Opera Safari
Basic support 40 ? 44
44
Service workers (and Push) have been disabled in the Firefox 45 and 52 Extended Support Releases (ESR).
No 24 11.1
Mobile
Android webview Chrome for Android Edge Mobile Firefox for Android Opera for Android iOS Safari Samsung Internet
Basic support 40 40 ? 44 24 11.1 4.0

See also

© 2005–2018 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerGlobalScope/onfetch