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:
- You can only return
Response
objects oftype
"opaque
" if thefetchEvent.request
object'smode
is "no-cors
". This prevents the leaking of private data. - You can only return
Response
objects oftype
"opaqueredirect
" if thefetchEvent.request
object'sredirectMode
is "manual
".
Syntax
fetchEvent.respondWith( // Promise that resolves to a Response. )
Parameters
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.)