W3cubDocs

/DOM

FetchEvent.respondWith

This is an experimental technology
Check the Browser compatibility table carefully before using this in production.

The respondWith() method of FetchEvent prevents the browser's default fetch handling, and allows you to provide a promise for a Response yourself.

In most cases you can provide any response that the receiver understands. For example, if an <img> initiates the request, the response body needs to be image data). For security reasons, there are a few global rules:

Syntax

fetchEvent.respondWith(
  // Promise that resolves to a Response.
​)

Parameters

A Promise for a Response.

Return value

Void.

Examples

This fetch event tries to return a response from the cache API, falling back to the network otherwise.

addEventListener('fetch', event => {
  // Prevent the default, and handle the request ourselves.
  event.respondWith(async function() {
    // Try to get the response from a cache.
    const cachedResponse = await caches.match(event.request);
    // Return it if we found one.
    if (cachedResponse) return cachedResponse;
    // If we didn't find a match in the cache, use the network.
    return fetch(event.request);
  }());
});

Specifications

Specification Status Comment
Service Workers
The definition of 'respondWith()' in that specification.
Editor's Draft Initial definition.

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support 40 44.0 (44.0)[1] No support 27 No support
Feature Android Webview Chrome for Android Firefox Mobile (Gecko) Firefox OS IE Mobile Opera Mobile Safari Mobile
Basic support 40 40 44.0 (44.0) (Yes) No support 27 No support

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

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/FetchEvent/respondWith