2021-01-07 11:46:05 -08:00
# class: Route
2021-01-14 07:48:56 -08:00
Whenever a network route is set up with [`method: Page.route` ] or [`method: BrowserContext.route` ], the `Route` object
allows to handle the route.
2021-01-07 11:46:05 -08:00
2022-05-11 16:07:00 +01:00
Learn more about [networking ](../network.md ).
2021-01-07 11:46:05 -08:00
## async method: Route.abort
Aborts the route's request.
### param: Route.abort.errorCode
2022-04-06 19:02:10 -07:00
- `errorCode` ?< [string]>
2021-01-07 11:46:05 -08:00
Optional error code. Defaults to `failed` , could be one of the following:
2021-01-14 07:48:56 -08:00
* `'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.
2021-01-07 11:46:05 -08:00
## async method: Route.continue
2021-01-08 15:00:14 -08:00
* langs:
2021-02-03 13:40:58 -08:00
- alias-java: resume
2021-01-08 15:00:14 -08:00
- alias-python: continue_
2021-01-07 11:46:05 -08:00
Continues route's request with optional overrides.
```js
await page.route('**/*', (route, request) => {
// Override headers
const headers = {
...request.headers(),
foo: 'bar', // set "foo" header
origin: undefined, // remove "origin" header
};
route.continue({headers});
});
```
2021-02-25 22:03:39 -08:00
```java
page.route("**/*", route -> {
// Override headers
Map< String , String > headers = new HashMap< >(route.request().headers());
headers.put("foo", "bar"); // set "foo" header
headers.remove("origin"); // remove "origin" header
2021-03-05 13:50:34 -08:00
route.resume(new Route.ResumeOptions().setHeaders(headers));
2021-02-25 22:03:39 -08:00
});
```
2021-01-14 07:48:56 -08:00
```python async
async def handle(route, request):
# override headers
headers = {
**request.headers,
"foo": "bar" # set "foo" header
"origin": None # remove "origin" header
}
2021-04-26 08:46:17 -07:00
await route.continue_(headers=headers)
2021-01-14 07:48:56 -08:00
}
await page.route("**/*", handle)
```
```python sync
def handle(route, request):
# override headers
headers = {
**request.headers,
"foo": "bar" # set "foo" header
"origin": None # remove "origin" header
}
2021-04-26 08:46:17 -07:00
route.continue_(headers=headers)
2021-01-14 07:48:56 -08:00
}
page.route("**/*", handle)
```
2021-05-14 16:49:14 +02:00
```csharp
await page.RouteAsync("**/*", route =>
{
var headers = new Dictionary< string , string > (route.Request.Headers) { { "foo", "bar" } };
headers.Remove("origin");
2021-05-17 20:10:32 -07:00
route.ContinueAsync(headers);
2021-05-14 16:49:14 +02:00
});
```
2021-01-08 16:17:54 -08:00
### option: Route.continue.url
- `url` < [string]>
If set changes the request URL. New URL must have same protocol as original one.
### option: Route.continue.method
- `method` < [string]>
If set changes the request method (e.g. GET or POST)
### option: Route.continue.postData
- `postData` < [string]|[Buffer]>
If set changes the post data of request
### option: Route.continue.headers
- `headers` < [Object]< [string], [string]>>
If set changes the request HTTP headers. Header values will be converted to a string.
2021-01-07 11:46:05 -08:00
2022-06-13 11:30:51 -08:00
## async method: Route.fallback
Proceeds to the next registered route in the route chain. If no more routes are
registered, continues the request as is. This allows registering multiple routes
with the same mask and falling back from one to another.
```js
// Handle GET requests.
await page.route('**/*', route => {
if (route.request().method() !== 'GET') {
route.fallback();
return;
}
// Handling GET only.
// ...
});
// Handle POST requests.
await page.route('**/*', route => {
if (route.request().method() !== 'POST') {
route.fallback();
return;
}
// Handling POST only.
// ...
});
```
```java
// 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.
// ...
});
```
```python async
# Handle GET requests.
def handle_post(route):
if route.request.method != "GET":
route.fallback()
return
# Handling GET only.
# ...
# Handle POST requests.
def handle_post(route):
if route.request.method != "POST":
route.fallback()
return
# Handling POST only.
# ...
await page.route("**/*", handle_get)
await page.route("**/*", handle_post)
```
```python sync
# Handle GET requests.
def handle_post(route):
if route.request.method != "GET":
route.fallback()
return
# Handling GET only.
# ...
# Handle POST requests.
def handle_post(route):
if route.request.method != "POST":
route.fallback()
return
# Handling POST only.
# ...
page.route("**/*", handle_get)
page.route("**/*", handle_post)
```
```csharp
// Handle GET requests.
await page.RouteAsync("**/*", route => {
if (route.Request.Method != "GET") {
await route.FallbackAsync();
return;
}
// Handling GET only.
// ...
});
// Handle POST requests.
await page.RouteAsync("**/*", route => {
if (route.Request.Method != "POST") {
await route.FallbackAsync();
return;
}
// Handling POST only.
// ...
});
```
2021-01-07 11:46:05 -08:00
## async method: Route.fulfill
Fulfills route's request with given response.
An example of fulfilling all requests with 404 responses:
```js
await page.route('**/*', route => {
route.fulfill({
status: 404,
contentType: 'text/plain',
body: 'Not Found!'
});
});
```
2021-02-25 22:03:39 -08:00
```java
page.route("**/*", route -> {
route.fulfill(new Route.FulfillOptions()
2021-03-05 13:50:34 -08:00
.setStatus(404)
.setContentType("text/plain")
.setBody("Not Found!"));
2021-02-25 22:03:39 -08:00
});
```
2021-01-14 07:48:56 -08:00
```python async
await page.route("**/*", lambda route: route.fulfill(
status=404,
content_type="text/plain",
body="not found!"))
```
```python sync
page.route("**/*", lambda route: route.fulfill(
status=404,
content_type="text/plain",
body="not found!"))
```
2021-05-14 16:49:14 +02:00
```csharp
await page.RouteAsync("**/*", route => route.FulfillAsync(
status: 404,
2022-04-06 19:02:10 -07:00
contentType: "text/plain",
2021-05-14 16:49:14 +02:00
body: "Not Found!"));
```
2021-01-07 11:46:05 -08:00
An example of serving static file:
```js
await page.route('**/xhr_endpoint', route => route.fulfill({ path: 'mock_data.json' }));
```
2021-02-25 22:03:39 -08:00
```java
page.route("**/xhr_endpoint", route -> route.fulfill(
2021-08-19 11:24:38 -07:00
new Route.FulfillOptions().setPath(Paths.get("mock_data.json"))));
2021-02-25 22:03:39 -08:00
```
2021-01-14 07:48:56 -08:00
```python async
await page.route("**/xhr_endpoint", lambda route: route.fulfill(path="mock_data.json"))
```
```python sync
page.route("**/xhr_endpoint", lambda route: route.fulfill(path="mock_data.json"))
```
2021-05-14 16:49:14 +02:00
```csharp
2021-05-19 17:19:25 -07:00
await page.RouteAsync("**/xhr_endpoint", route => route.FulfillAsync(new RouteFulfillOptions { Path = "mock_data.json" }));
2021-05-14 16:49:14 +02:00
```
2021-01-08 16:17:54 -08:00
### option: Route.fulfill.status
- `status` < [int]>
Response status code, defaults to `200` .
### option: Route.fulfill.headers
- `headers` < [Object]< [string], [string]>>
Response headers. Header values will be converted to a string.
### option: Route.fulfill.contentType
- `contentType` < [string]>
If set, equals to setting `Content-Type` response header.
### option: Route.fulfill.body
2021-02-03 14:56:17 -08:00
* langs: js, python
2021-01-08 16:17:54 -08:00
- `body` < [string]|[Buffer]>
Response body.
2021-02-03 14:56:17 -08:00
### option: Route.fulfill.body
* langs: csharp, java
- `body` < [string]>
Optional response body as text.
### option: Route.fulfill.bodyBytes
* langs: csharp, java
- `bodyBytes` < [Buffer]>
Optional response body as raw bytes.
2022-06-08 20:29:03 -07:00
### option: Route.fulfill.har
2022-06-10 16:53:01 -07:00
* langs: js
2022-06-10 14:26:45 -07:00
- `har` < [Object]>
- `path` < [string]> Path to the HAR file.
- `fallback` ?< [RouteHARFallback]< "abort"|"continue"|"throw">> Behavior in the case where matching entry was not found in the HAR. Either [`method: Route.abort` ] the request, [`method: Route.continue` ] it, or throw an error. Defaults to "abort".
2022-06-08 20:29:03 -07:00
2022-06-10 14:26:45 -07:00
HAR file to extract the response from. If HAR file contains an entry with the matching url and HTTP method, then the entry's headers, status and body will be used to fulfill. An entry resulting in a redirect will be followed automatically. Individual fields such as headers can be overridden using fulfill options.
If `path` is a relative path, then it is resolved relative to the current working directory.
2022-06-08 20:29:03 -07:00
2022-06-10 16:53:01 -07:00
### option: Route.fulfill.harPath
* langs: csharp, java, python
- alias-python: har_path
- `harPath` < [path]>
HAR file to extract the response from. If HAR file contains an entry with the matching url and HTTP method, then the entry's headers, status and body will be used to fulfill. An entry resulting in a redirect will be followed automatically. Individual fields such as headers can be overridden using fulfill options.
If `path` is a relative path, then it is resolved relative to the current working directory.
### option: Route.fulfill.harFallback
* langs: csharp, java, python
- alias-python: har_fallback
- `harFallback` ?< [RouteHARFallback]< "abort"|"continue"|"throw">>
Behavior in the case where matching entry was not found in the HAR. Either [`method: Route.abort` ] the request, [`method: Route.continue` ] it, or throw an error. Defaults to "abort".
2021-01-08 16:17:54 -08:00
### option: Route.fulfill.path
- `path` < [path]>
2021-01-07 11:46:05 -08:00
2021-01-14 07:48:56 -08:00
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.
2021-01-07 11:46:05 -08:00
2021-09-10 18:36:55 -07:00
### option: Route.fulfill.response
2021-10-19 11:17:23 -07:00
- `response` < [APIResponse]>
2021-09-10 18:36:55 -07:00
2021-10-19 11:17:23 -07:00
[APIResponse] to fulfill route's request with. Individual fields of the response (such as headers) can be overridden using fulfill options.
2021-09-10 18:36:55 -07:00
2021-01-07 11:46:05 -08:00
## method: Route.request
- returns: < [Request]>
A request to be routed.