Playwright Network Interception
Playwright's Network Interception is a very useful capability in automated testing and web scraping scenarios, allowing us to intercept, modify, and simulate network requests and responses.
Playwright provides APIs such as `page.route()` and `page.on('request')` / `page.on('response')`, which can:
* **Intercept Requests**: Decide whether to allow, modify URL/headers/body, or directly return mock responses.
* **Monitor Requests/Responses**: View request URL, method, headers, response status code, response body, etc.
* **Simulate Network Errors**: Block requests, return error codes, test the application's fault tolerance logic.
Common application scenarios:
* **Mock API**: Run frontend UI tests without backend APIs.
* **Modify Requests**: For example, add tokens, test abnormal headers.
* **Performance Debugging**: Count number of requests, response times.
* **Error Injection**: Simulate server-side exceptions like 500/404.
### Intercept Requests: page.route()
await page.route('**/api/todos', async route => { // Intercept matching requests console.log('Intercepted request:', route.request().url()); // 1. Allow request to proceed (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. Abort request // await route.abort();});
**Parameter Description**:
* `page.route(url, handler)`: Register an interceptor, `url` supports string, regex, or `**` wildcard.
* `route.request()`: Get the request object.
* `route.continue()`: Allow request to proceed, can modify method, headers, postData.
* `route.fulfill(response)`: Directly return a fabricated response.
* `route.abort()`: Abort the request, common error codes like `"failed"`, `"aborted"`, `"timedout"`.
### Monitor Requests and Responses
// Monitor all requests page.on('request', req => { console.log(`➡️ Request: ${req.method()} ${req.url()}`);});// Monitor all responses page.on('response', async res => { console.log(`⬅️ Response: ${res.status()} ${res.url()}`);});// Get response bodyconst response = await page.waitForResponse('**/api/data'); console.log('Response content:', await response.text());
**Common Methods**:
* `request.url()` / `request.method()` / `request.headers()` / `request.postData()`
* `response.status()` / `response.headers()` / `response.text()` / `response.json()`
### Simulate Network Environment
## Example
// Simulate network error
await page.route('**/*.png', route => route.abort('failed'));
// Simulate delay
await page.route('**/api/**', async route =>{
await new Promise(r => setTimeout(r,2000));
await route.continue();
});
YouTip