Route
Whenever a network route is set up with Page.route() or BrowserContext.route(), the Route
object allows to handle the route.
Learn more about networking.
Methods
abort
Added before v1.9Aborts the route's request.
Usage
Route.abort();
Route.abort(errorCode);
Arguments
-
Optional error code. Defaults to
failed
, could be one of the following:'aborted'
- An operation was aborted (due to user action)'accessdenied'
- Permission to access a resource, other than the network, was denied'addressunreachable'
- The IP address is unreachable. This usually means that there is no route to the specified host or network.'blockedbyclient'
- The client chose to block the request.'blockedbyresponse'
- The request failed because the response was delivered along with requirements which are not met ('X-Frame-Options' and 'Content-Security-Policy' ancestor checks, for instance).'connectionaborted'
- A connection timed out as a result of not receiving an ACK for data sent.'connectionclosed'
- A connection was closed (corresponding to a TCP FIN).'connectionfailed'
- A connection attempt failed.'connectionrefused'
- A connection attempt was refused.'connectionreset'
- A connection was reset (corresponding to a TCP RST).'internetdisconnected'
- The Internet connection has been lost.'namenotresolved'
- The host name could not be resolved.'timedout'
- An operation timed out.'failed'
- A generic failure occurred.
Returns
fallback
Added in: v1.23Continues route's request with optional overrides. The method is similar to Route.resume() with the difference that other matching handlers will be invoked before sending the request.
Usage
When several routes match the given pattern, they run in the order opposite to their registration. That way the last registered route can always override all the previous ones. In the example below, request will be handled by the bottom-most handler first, then it'll fall back to the previous one and in the end will be aborted by the first registered route.
page.route("**/*", route -> {
// Runs last.
route.abort();
});
page.route("**/*", route -> {
// Runs second.
route.fallback();
});
page.route("**/*", route -> {
// Runs first.
route.fallback();
});
Registering multiple routes is useful when you want separate handlers to handle different kinds of requests, for example API calls vs page resources or GET requests vs POST requests as in the example below.
// Handle GET requests.
page.route("**/*", route -> {
if (!route.request().method().equals("GET")) {
route.fallback();
return;
}
// Handling GET only.
// ...
});
// Handle POST requests.
page.route("**/*", route -> {
if (!route.request().method().equals("POST")) {
route.fallback();
return;
}
// Handling POST only.
// ...
});
One can also modify request while falling back to the subsequent handler, that way intermediate route handler can modify url, method, headers and postData of the request.
page.route("**/*", route -> {
// Override headers
Map<String, String> headers = new HashMap<>(route.request().headers());
headers.put("foo", "foo-value"); // set "foo" header
headers.remove("bar"); // remove "bar" header
route.fallback(new Route.ResumeOptions().setHeaders(headers));
});
Use Route.resume() to immediately send the request to the network, other matching handlers won't be invoked in that case.
Arguments
options
Route.FallbackOptions
(optional)-
setHeaders
Map<String, String> (optional)#If set changes the request HTTP headers. Header values will be converted to a string.
-
If set changes the request method (e.g. GET or POST).
-
setPostData
String | byte[] (optional)#If set changes the post data of request.
-
If set changes the request URL. New URL must have same protocol as original one. Changing the URL won't affect the route matching, all the routes are matched using the original request URL.
-
Returns
fetch
Added in: v1.29Performs the request and fetches result without fulfilling it, so that the response could be modified and then fulfilled.
Usage
page.route("https://dog.ceo/api/breeds/list/all", route -> {
APIResponse response = route.fetch();
JsonObject json = new Gson().fromJson(response.text(), JsonObject.class);
JsonObject message = itemObj.get("json").getAsJsonObject();
message.set("big_red_dog", new JsonArray());
route.fulfill(new Route.FulfillOptions()
.setResponse(response)
.setBody(json.toString()));
});
Arguments
options
Route.FetchOptions
(optional)-
setHeaders
Map<String, String> (optional)#If set changes the request HTTP headers. Header values will be converted to a string.
-
setMaxRedirects
int (optional) Added in: v1.31#Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is exceeded. Defaults to
20
. Pass0
to not follow redirects. -
setMaxRetries
int (optional) Added in: v1.46#Maximum number of times network errors should be retried. Currently only
ECONNRESET
error is retried. Does not retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to0
- no retries. -
If set changes the request method (e.g. GET or POST).
-
setPostData
String | byte[] (optional)#If set changes the post data of request.
-
setTimeout
double (optional) Added in: v1.33#Request timeout in milliseconds. Defaults to
30000
(30 seconds). Pass0
to disable timeout. -
If set changes the request URL. New URL must have same protocol as original one.
-
Returns
Details
Note that headers
option will apply to the fetched request as well as any redirects initiated by it. If you want to only apply headers
to the original request, but not to redirects, look into Route.resume() instead.
fulfill
Added before v1.9Fulfills route's request with given response.
Usage
An example of fulfilling all requests with 404 responses:
page.route("**/*", route -> {
route.fulfill(new Route.FulfillOptions()
.setStatus(404)
.setContentType("text/plain")
.setBody("Not Found!"));
});
An example of serving static file:
page.route("**/xhr_endpoint", route -> route.fulfill(
new Route.FulfillOptions().setPath(Paths.get("mock_data.json"))));
Arguments
options
Route.FulfillOptions
(optional)-
Optional response body as text.
-
setBodyBytes
byte[] (optional) Added in: v1.9#Optional response body as raw bytes.
-
setContentType
String (optional)#If set, equals to setting
Content-Type
response header. -
setHeaders
Map<String, String> (optional)#Response headers. Header values will be converted to a string.
-
File path to respond with. The content type will be inferred from file extension. If
path
is a relative path, then it is resolved relative to the current working directory. -
setResponse
APIResponse (optional) Added in: v1.15#APIResponse to fulfill route's request with. Individual fields of the response (such as headers) can be overridden using fulfill options.
-
Response status code, defaults to
200
.
-
Returns
request
Added before v1.9A request to be routed.
Usage
Route.request();
Returns
resume
Added before v1.9Sends route's request to the network with optional overrides.
Usage
page.route("**/*", route -> {
// Override headers
Map<String, String> headers = new HashMap<>(route.request().headers());
headers.put("foo", "foo-value"); // set "foo" header
headers.remove("bar"); // remove "bar" header
route.resume(new Route.ResumeOptions().setHeaders(headers));
});
Arguments
options
Route.ResumeOptions
(optional)-
setHeaders
Map<String, String> (optional)#If set changes the request HTTP headers. Header values will be converted to a string.
-
If set changes the request method (e.g. GET or POST).
-
setPostData
String | byte[] (optional)#If set changes the post data of request.
-
If set changes the request URL. New URL must have same protocol as original one.
-
Returns
Details
Note that any overrides such as url
or headers
only apply to the request being routed. If this request results in a redirect, overrides will not be applied to the new redirected request. If you want to propagate a header through redirects, use the combination of Route.fetch() and Route.fulfill() instead.
Route.resume() will immediately send the request to the network, other matching handlers won't be invoked. Use Route.fallback() If you want next matching handler in the chain to be invoked.