respondWith method
@AvailableInWorkers("service")
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
Responseobjects ofResponse.type"opaque" if thefetchEvent.requestobject'srequest.modeis "no-cors". This prevents the leaking of private data. - You can only return
Responseobjects ofResponse.type"opaqueredirect" if thefetchEvent.requestobject'srequest.modeis "manual". - You cannot return
Responseobjects ofResponse.type"cors" if thefetchEvent.requestobject'srequest.modeis "same-origin".
Specifying the final URL of a resource
From Firefox 59 onwards, when a service worker provides a Response to
FetchEvent.respondWith, the Response.url value will be
propagated to the intercepted network request as the final resolved URL.
If the
Response.url value is the empty string, then the
Request.url is used as the final URL.
In the past the Request.url was used as the
final URL in all cases. The provided Response.url was effectively
ignored.
This means, for example, if a service worker intercepts a stylesheet or
worker script,
then the provided Response.url will be used to resolve any relative
or
WorkerGlobalScope.importScripts subresource loads
(Firefox bug 1222008).
For most types of network request this change has no impact because you can't observe the final URL. There are a few, though, where it does matter:
- If a
fetchis intercepted, then you can observe the final URL on the result'sResponse.url. - If a
worker
script is
intercepted, then the final URL is used to set
self.locationand used as the base URL for relative URLs in the worker script. - If a stylesheet is intercepted, then the final URL is used as the base URL for resolving relative loads.
Note that navigation requests for Window and HTMLIFrameElement do NOT use the final URL. The way the HTML specification handles redirects for navigations ends up using the request URL for the resulting Window.location. This means sites can still provide an "alternate" view of a web page when offline without changing the user-visible URL.
Implementation
external void respondWith(JSPromise<Response> r);