ServiceWorkerGlobalScope.onfetch

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

Syntax

serviceWorkerGlobalScope.onfetch = function(fetchEvent) { ... };

Example

This code snippet is from the service worker prefetch 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 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

DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
onfetch
Experimental
Chrome Full support 40Edge Full support ≤79Firefox Full support 44
Notes
Full support 44
Notes
Notes Extended Support Releases (ESR) before Firefox 78 ESR do not support service workers and the Push API.
IE No support NoOpera Full support 24Safari Full support 11.1WebView Android Full support 40Chrome Android Full support 40Firefox Android Full support 44Opera Android Full support 24Safari iOS Full support 11.3Samsung Internet Android Full support 4.0

Legend

Full support
Full support
No support
No support
Experimental. Expect behavior to change in the future.
Experimental. Expect behavior to change in the future.
See implementation notes.
See implementation notes.

See also