FetchEvent
Baseline Widely available *
This feature is well established and works across many devices and browser versions. It’s been available across browsers since April 2018.
* Some parts of this feature may have varying levels of support.
Note: This feature is only available inService Workers.
This is the event type forfetch events dispatched on theservice worker global scope. It contains information about the fetch, including the request and how the receiver will treat the response. It provides theevent.respondWith() method, which allows us to provide a response to this fetch.
In this article
Constructor
FetchEvent()Creates a new
FetchEventobject. This constructor is not typically used. The browser creates these objects and provides them tofetchevent callbacks.
Instance properties
Inherits properties from its ancestor,Event.
FetchEvent.clientIdRead onlyFetchEvent.handledRead onlyA promise that is pending while the event has not been handled, and fulfilled once it has.
FetchEvent.isReloadRead onlyDeprecatedNon-standardReturns
trueif the event was dispatched by the user attempting to reload the page, andfalseotherwise.FetchEvent.preloadResponseRead onlyA
Promisefor aResponse, orundefinedif this fetch is not a navigation, ornavigation preload is not enabled.FetchEvent.replacesClientIdRead onlyThe
idof theclientthat is being replaced during a page navigation.FetchEvent.resultingClientIdRead onlyThe
idof theclientthat replaces the previous client during a page navigation.FetchEvent.requestRead onlyThe
Requestthe browser intends to make.
Instance methods
Inherits methods from its parent,ExtendableEvent.
FetchEvent.respondWith()Prevent the browser's default fetch handling, and provide (a promise for) a response yourself.
ExtendableEvent.waitUntil()Extends the lifetime of the event. Used to notify the browser of tasks that extend beyond the returning of a response, such as streaming and caching.
Examples
This fetch event uses the browser default for non-GET requests.For GET requests it tries to return a match in the cache, and falls back to the network. If it finds a match in the cache, it asynchronously updates the cache for next time.
self.addEventListener("fetch", (event) => { // Let the browser do its default thing // for non-GET requests. if (event.request.method !== "GET") return; // Prevent the default, and handle the request ourselves. event.respondWith( (async () => { // Try to get the response from a cache. const cache = await caches.open("dynamic-v1"); const cachedResponse = await cache.match(event.request); if (cachedResponse) { // If we found a match in the cache, return it, but also // update the entry in the cache in the background. event.waitUntil(cache.add(event.request)); return cachedResponse; } // If we didn't find a match in the cache, use the network. return fetch(event.request); })(), );});Specifications
| Specification |
|---|
| Service Workers Nightly> # fetchevent-interface> |