Playwright Network Interception
Playwright's network interception (Network Interception) is a very useful capability in automation testing and web scraping scenarios, allowing us to intercept, modify, and simulate network requests and responses.
Playwright provides a page.route() and page.on('request') / page.on('response') and other APIs, allowing you to:
- Intercept requests: decide whether to allow, modify URL/headers/body, or directly return a mock response.
- Listen to requests/responses: view the request's URL, method, headers, response status code, response body, etc.
- Simulate network errors: block requests, return error codes, and test the application's fault-tolerance logic.
Common use cases:
- Mock API: run front-end UI tests without a backend API.
- Modify requests: for example, add a token or test abnormal headers.
- Performance debugging: count requests and measure response times.
- Error injection: simulate server errors such as 500/404.
Intercepting requests: page.route()
await page.route('**/api/todos', async route => {
// Intercept matching requests
console.log('拦截到请求:', route.request().url());
// 1. Allow directly (continue request)
await route.continue();
// 2. Modify request
// await route.continue({ headers: { ...route.request().headers(), 'X-Test': 'true' } });
// 3. Return mock response
// await route.fulfill({
// status: 200,
// contentType: 'application/json',
// body: JSON.stringify([{ id: 1, text: 'mock todo', done: false }]),
// });
// 4. Reject request
// await route.abort();
});
Parameter Description:
page.route(url, handler): register an interceptor,urlsupports strings, regular expressions, or**wildcards.route.request(): get the request object.route.continue([options]): continue the request, allowing modification of the method, headers, and postData.route.fulfill(response): directly return a fabricated response.route.abort([errorCode]): abort the request, with common error codes such as"failed","aborted","timedout"。
Listen to requests and responses
// Listen to all requests
page.on('request', req => {
console.log(`➡️ 请求: ${req.method()} ${req.url()}`);
});
// Listen to all responses
page.on('response', async res => {
console.log(`⬅️ 响应: ${res.status()} ${res.url()}`);
});
// Get response body
const response = await page.waitForResponse('**/api/data');
console.log('响应内容:', await response.text());
// 2022-01-01 00:00:00 GMT:
request.url()/request.method()/request.headers()/request.postData()response.status()/response.headers()/response.text()/response.json()
Simulate network conditions
Example
// Simulate network errors
await page.
route
(
'**/*.png'
,
route
=>
route.
abort
(
'failed'
)
)
;
// Simulate latency
await page.
route
(
'/api/'
,
async route
=>
{
await
new
Promise
(
r
=>
setTimeout
(
r
,
2000
)
)
;
await route.
continue
(
)
;
}
)
;
pre
<
hr
<
h2Complete example: Mock API
h2
import
{
test
,
expect
}
from
'@playwright/test'
;
test
(
'Intercept and mock API'
,
async
(
{
page
}
)
=>
{
// Intercept /api/todos requests and return fixed data
await page.
route
(
'**/api/todos'
,
async route
=>
{
await route.
fulfill
(
{
status
:
200
,
contentType
:
'application/json'
,
body
:
JSON.
stringify
(
[
{
id
:
1
,
text
:
'Playwright Learning'
,
done
:
false
}
,
{
id
:
2
,
text
:
'Write automation tests'
,
done
:
true
}
,
]
)
,
}
)
;
}
)
;
await page.
goto
(
'https://example-todo-app.com'
)
;
const
items
=
await page.
locator
(
'.todo-item'
)
.
allTextContents
(
)
;
console.
log
(
'Loaded todos:'
,
items
)
;
// Assert UI displays mock data
await expect
(
page.
locator
(
'.todo-item'
)
)
.
toHaveCount
(
2
)
;
await expect
(
page.
locator
(
'.todo-item'
)
.
first
(
)
)
.
toContainText
(
'Playwright Learning'
)
;
}
)
;
Network interception related APIs
| API | Purpose | Common parameters/descriptions |
|---|---|---|
page.route(url, handler) |
Register request interception | url Can be a string/regex/wildcard |
route.request() |
Get request object | Return Request |
route.continue([options]) |
Continue request, can modify | { method, headers, postData } |
route.fulfill(response) |
Return a custom response | { status, headers, body, contentType } |
route.abort([errorCode]) |
Abort request | Common:'failed', 'aborted', 'timedout' |
page.unroute(url, handler?) |
Remove interception rule | |
page.on('request', cb) |
Listen to request | |
page.on('response', cb) |
Listen to response | |
request.url()/method()/headers()/postData() |
Request information | |
response.status()/headers()/text()/json() |
Response information | |
page.waitForResponse(urlOrPredicate) |
Wait for a specific response | Can pass a URL or function |