WorkerGlobalScope: fetch() method
Baseline Widely available *
This feature is well established and works across many devices and browser versions. It’s been available across browsers since March 2017.
* Some parts of this feature may have varying levels of support.
Note: This feature is only available inWeb Workers.
Thefetch() method of theWorkerGlobalScope interface starts the process of fetching a resource from the network, returning a promise that is fulfilled once the response is available.
The promise resolves to theResponse object representing the response to your request.
Afetch() promise only rejects when the request fails, for example, because of a badly-formed request URL or a network error.Afetch() promisedoes not reject if the server responds with HTTP status codes that indicate errors (404,504, etc.).Instead, athen() handler must check theResponse.ok and/orResponse.status properties.
Thefetch() method is controlled by theconnect-src directive ofContent Security Policy rather than the directive of the resources it's retrieving.
Note:Thefetch() method's parameters are identical to those of theRequest() constructor.
In this article
Syntax
fetch(resource)fetch(resource, options)Parameters
resourceThis defines the resource that you wish to fetch. This can either be:
- A string or any other object with astringifier — including a
URLobject — that provides the URL of the resource you want to fetch. The URL may be relative to the base URL, which is the document'sbaseURIin a window context, orWorkerGlobalScope.locationin a worker context. - A
Requestobject.
- A string or any other object with astringifier — including a
optionsOptionalA
RequestInitobject containing any custom settings that you want to apply to the request.
Return value
Exceptions
AbortErrorDOMExceptionThe request was aborted due to a call to the
AbortControllerabort()method.NotAllowedErrorDOMExceptionThrown if use of theTopics API is specifically disallowed by a
browsing-topicsPermissions Policy, and afetch()request was made withbrowsingTopics: true.TypeErrorAn error when the fetch operation could not be performed.See
Window.fetch()exceptions for a list of reasons why this error can occur.
Examples
Seefetch() for examples.
Specifications
| Specification |
|---|
| Fetch> # fetch-method> |