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 compatibility

FeatureChromeEdgeFirefoxInternet ExplorerOperaSafari
Basic support40 ?441 No24 No
FeatureAndroid webviewChrome for AndroidEdge mobileFirefox for AndroidOpera AndroidiOS SafariSamsung Internet
Basic support4040 ?4424 No4.0

1. Service workers (and Push) have been disabled in the Firefox 45 and 52 Extended Support Releases (ESR).

 

See also

Document Tags and Contributors

Contributors to this page: fscholz, chrisdavidmills, Sebastianz, kscarfone, jpmedley
Last updated by: fscholz,