2021-01-02 02:17:27 +03:00
---
id: network
title: "Network"
---
2020-12-31 05:04:51 +03:00
2022-09-29 16:42:01 +03:00
Playwright provides APIs to **monitor** and **modify** network traffic, both HTTP and HTTPS. Any requests that a page does, including [XHRs ](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest ) and
2020-12-31 05:04:51 +03:00
[fetch ](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API ) requests, can be tracked, modified and handled.
## HTTP Authentication
2022-12-22 05:19:02 +03:00
Perform HTTP Authentication.
2022-09-29 16:42:01 +03:00
2022-12-22 05:19:02 +03:00
```js tab=js-ts
2023-01-13 00:12:02 +03:00
import { defineConfig } from '@playwright/test';
export default defineConfig({
2022-12-22 05:19:02 +03:00
use: {
httpCredentials: {
username: 'bill',
password: 'pa55w0rd',
}
}
2023-01-13 00:12:02 +03:00
});
2022-12-22 05:19:02 +03:00
```
```js tab=js-library
2020-12-31 05:04:51 +03:00
const context = await browser.newContext({
httpCredentials: {
username: 'bill',
password: 'pa55w0rd',
},
});
const page = await context.newPage();
await page.goto('https://example.com');
```
2021-03-01 20:18:44 +03:00
```java
BrowserContext context = browser.newContext(new Browser.NewContextOptions()
2021-03-06 00:50:34 +03:00
.setHttpCredentials("bill", "pa55w0rd"));
2021-03-01 20:18:44 +03:00
Page page = context.newPage();
page.navigate("https://example.com");
```
2021-01-15 02:01:39 +03:00
```python async
context = await browser.new_context(
http_credentials={"username": "bill", "password": "pa55w0rd"}
)
page = await context.new_page()
await page.goto("https://example.com")
```
```python sync
context = browser.new_context(
http_credentials={"username": "bill", "password": "pa55w0rd"}
)
page = context.new_page()
page.goto("https://example.com")
```
2020-12-31 05:04:51 +03:00
2021-05-15 09:22:30 +03:00
```csharp
2022-07-13 12:50:18 +03:00
using var context = await Browser.NewContextAsync(new()
2021-05-15 09:22:30 +03:00
{
HttpCredentials = new HttpCredentials
{
Username = "bill",
Password = "pa55w0rd"
},
});
var page = await context.NewPageAsync();
await page.GotoAsync("https://example.com");
```
2021-03-02 07:14:19 +03:00
## HTTP Proxy
You can configure pages to load over the HTTP(S) proxy or SOCKSv5. Proxy can be either set globally
for the entire browser, or for each browser context individually.
You can optionally specify username and password for HTTP(S) proxy, you can also specify hosts to
bypass proxy for.
Here is an example of a global proxy:
2022-12-23 12:57:29 +03:00
```js tab=js-ts
2023-01-13 00:12:02 +03:00
import { defineConfig } from '@playwright/test';
export default defineConfig({
2022-12-23 12:57:29 +03:00
use: {
proxy: {
server: 'http://myproxy.com:3128',
username: 'usr',
password: 'pwd'
}
}
2023-01-13 00:12:02 +03:00
});
2022-12-23 12:57:29 +03:00
```
```js tab=js-library
2021-03-02 07:14:19 +03:00
const browser = await chromium.launch({
proxy: {
server: 'http://myproxy.com:3128',
2021-05-24 19:35:58 +03:00
username: 'usr',
2021-03-02 07:14:19 +03:00
password: 'pwd'
}
});
```
```java
Browser browser = chromium.launch(new BrowserType.LaunchOptions()
2021-03-06 00:50:34 +03:00
.setProxy(new Proxy("http://myproxy.com:3128")
.setUsername('usr')
.setPassword('pwd'));
2021-03-02 07:14:19 +03:00
```
```python async
browser = await chromium.launch(proxy={
"server": "http://myproxy.com:3128",
2021-05-24 19:35:58 +03:00
"username": "usr",
2021-03-02 07:14:19 +03:00
"password": "pwd"
})
```
```python sync
browser = chromium.launch(proxy={
"server": "http://myproxy.com:3128",
2021-05-24 19:35:58 +03:00
"username": "usr",
2021-03-02 07:14:19 +03:00
"password": "pwd"
})
```
2021-05-15 09:22:30 +03:00
```csharp
var proxy = new Proxy
{
Server = "http://myproxy.com:3128",
Username = "user",
Password = "pwd"
};
2022-07-13 12:50:18 +03:00
await using var browser = await BrowserType.LaunchAsync(new()
2021-05-20 03:19:25 +03:00
{
Proxy = proxy
});
2021-05-15 09:22:30 +03:00
```
2021-10-26 02:32:09 +03:00
When specifying proxy for each context individually, **Chromium on Windows** needs a hint that proxy will be set. This is done via passing a non-empty proxy server to the browser itself. Here is an example of a context-specific proxy:
2021-03-02 07:14:19 +03:00
2022-12-23 12:57:29 +03:00
```js tab=js-ts
2023-01-13 00:12:02 +03:00
import { defineConfig } from '@playwright/test';
export default defineConfig({
2022-12-23 12:57:29 +03:00
use: {
launchOptions: {
// Browser proxy option is required for Chromium on Windows.
proxy: { server: 'per-context' }
},
proxy: {
server: 'http://myproxy.com:3128',
}
}
2023-01-13 00:12:02 +03:00
});
2022-12-23 12:57:29 +03:00
```
```js tab=js-library
2021-03-02 07:14:19 +03:00
const browser = await chromium.launch({
2021-10-26 02:32:09 +03:00
// Browser proxy option is required for Chromium on Windows.
2021-03-02 07:14:19 +03:00
proxy: { server: 'per-context' }
});
const context = await browser.newContext({
proxy: { server: 'http://myproxy.com:3128' }
})
```
```java
Browser browser = chromium.launch(new BrowserType.LaunchOptions()
2021-10-26 02:32:09 +03:00
// Browser proxy option is required for Chromium on Windows.
2021-03-06 00:50:34 +03:00
.setProxy(new Proxy("per-context"));
2021-03-02 07:14:19 +03:00
BrowserContext context = chromium.launch(new Browser.NewContextOptions()
2021-03-06 00:50:34 +03:00
.setProxy(new Proxy("http://myproxy.com:3128"));
2021-03-02 07:14:19 +03:00
```
```python async
2021-10-26 02:32:09 +03:00
# Browser proxy option is required for Chromium on Windows.
2021-03-02 07:14:19 +03:00
browser = await chromium.launch(proxy={"server": "per-context"})
context = await browser.new_context(proxy={"server": "http://myproxy.com:3128"})
```
```python sync
2021-10-26 02:32:09 +03:00
# Browser proxy option is required for Chromium on Windows.
2021-03-02 07:14:19 +03:00
browser = chromium.launch(proxy={"server": "per-context"})
context = browser.new_context(proxy={"server": "http://myproxy.com:3128"})
```
2021-05-15 09:22:30 +03:00
```csharp
var proxy = new Proxy { Server = "per-context" };
2022-07-13 12:50:18 +03:00
await using var browser = await BrowserType.LaunchAsync(new()
2021-05-20 03:19:25 +03:00
{
2021-10-26 02:32:09 +03:00
// Browser proxy option is required for Chromium on Windows.
2021-05-20 03:19:25 +03:00
Proxy = proxy
});
2022-07-13 12:50:18 +03:00
using var context = await Browser.NewContextAsync(new()
2021-05-20 03:19:25 +03:00
{
Proxy = new Proxy { Server = "http://myproxy.com:3128" })
});
2021-05-15 09:22:30 +03:00
```
2020-12-31 05:04:51 +03:00
## Network events
2022-09-29 16:42:01 +03:00
You can monitor all the [Request]s and [Response]s:
2020-12-31 05:04:51 +03:00
```js
2022-12-23 12:57:29 +03:00
// Subscribe to 'request' and 'response' events.
page.on('request', request => console.log('>>', request.method(), request.url()));
page.on('response', response => console.log('< < ', response.status(), response.url()));
2020-12-31 05:04:51 +03:00
2022-12-23 12:57:29 +03:00
await page.goto('https://example.com');
2020-12-31 05:04:51 +03:00
```
2021-03-01 20:18:44 +03:00
```java
import com.microsoft.playwright.*;
public class Example {
public static void main(String[] args) {
try (Playwright playwright = Playwright.create()) {
BrowserType chromium = playwright.chromium();
Browser browser = chromium.launch();
Page page = browser.newPage();
page.onRequest(request -> System.out.println(">> " + request.method() + " " + request.url()));
page.onResponse(response -> System.out.println("< < " + response.status() + " " + response.url()));
page.navigate("https://example.com");
browser.close();
}
}
}
```
2021-01-15 02:01:39 +03:00
```python async
import asyncio
from playwright.async_api import async_playwright
async def run(playwright):
chromium = playwright.chromium
browser = await chromium.launch()
page = await browser.new_page()
# Subscribe to "request" and "response" events.
page.on("request", lambda request: print(">>", request.method, request.url))
page.on("response", lambda response: print("< < ", response.status, response.url))
await page.goto("https://example.com")
await browser.close()
async def main():
async with async_playwright() as playwright:
await run(playwright)
asyncio.run(main())
```
```python sync
from playwright.sync_api import sync_playwright
def run(playwright):
chromium = playwright.chromium
browser = chromium.launch()
page = browser.new_page()
# Subscribe to "request" and "response" events.
page.on("request", lambda request: print(">>", request.method, request.url))
page.on("response", lambda response: print("< < ", response.status, response.url))
page.goto("https://example.com")
browser.close()
with sync_playwright() as playwright:
run(playwright)
```
2021-05-15 09:22:30 +03:00
```csharp
using Microsoft.Playwright;
2022-04-19 21:23:26 +03:00
using var playwright = await Playwright.CreateAsync();
await using var browser = await playwright.Chromium.LaunchAsync();
var page = await browser.NewPageAsync();
page.Request += (_, request) => Console.WriteLine(">> " + request.Method + " " + request.Url);
page.Response += (_, response) => Console.WriteLine("< < " + response.Status + " " + response.Url);
await page.GotoAsync("https://example.com");
2021-05-15 09:22:30 +03:00
```
2022-09-29 16:42:01 +03:00
Or wait for a network response after the button click with [`method: Page.waitForResponse`]:
2020-12-31 05:04:51 +03:00
```js
2022-11-30 23:36:35 +03:00
// Use a glob URL pattern. Note no await.
const responsePromise = page.waitForResponse('**/api/fetch_data');
await page.getByText('Update').click();
const response = await responsePromise;
2020-12-31 05:04:51 +03:00
```
2021-03-01 20:18:44 +03:00
```java
// Use a glob URL pattern
Response response = page.waitForResponse("**/api/fetch_data", () -> {
2022-10-04 03:02:46 +03:00
page.getByText("Update").click();
2021-03-01 20:18:44 +03:00
});
```
2021-01-15 02:01:39 +03:00
```python async
# Use a glob url pattern
async with page.expect_response("**/api/fetch_data") as response_info:
2022-10-04 03:02:46 +03:00
await page.get_by_text("Update").click()
2021-01-15 02:01:39 +03:00
response = await response_info.value
```
```python sync
# Use a glob url pattern
with page.expect_response("**/api/fetch_data") as response_info:
2022-10-04 03:02:46 +03:00
page.get_by_text("Update").click()
2021-01-15 02:01:39 +03:00
response = response_info.value
```
2021-05-15 09:22:30 +03:00
```csharp
// Use a glob URL pattern
2021-05-15 21:57:20 +03:00
var waitForResponseTask = page.WaitForResponseAsync("**/api/fetch_data");
2022-10-04 03:02:46 +03:00
await page.GetByText("Update").ClickAsync();
2021-05-16 00:02:07 +03:00
var response = await waitForResponseTask;
2021-05-15 09:22:30 +03:00
```
2020-12-31 05:04:51 +03:00
#### Variations
2022-09-29 16:42:01 +03:00
Wait for [Response]s with [`method: Page.waitForResponse`]
2020-12-31 05:04:51 +03:00
```js
2022-11-30 23:36:35 +03:00
// Use a RegExp. Note no await.
const responsePromise = page.waitForResponse(/\.jpeg$/);
await page.getByText('Update').click();
const response = await responsePromise;
// Use a predicate taking a Response object. Note no await.
const responsePromise = page.waitForResponse(response => response.url().includes(token));
await page.getByText('Update').click();
const response = await responsePromise;
2020-12-31 05:04:51 +03:00
```
2021-03-01 20:18:44 +03:00
```java
// Use a RegExp
Response response = page.waitForResponse(Pattern.compile("\\.jpeg$"), () -> {
2022-10-04 03:02:46 +03:00
page.getByText("Update").click();
2021-03-01 20:18:44 +03:00
});
// Use a predicate taking a Response object
Response response = page.waitForResponse(r -> r.url().contains(token), () -> {
2022-10-04 03:02:46 +03:00
page.getByText("Update").click();
2021-03-01 20:18:44 +03:00
});
```
2021-01-15 02:01:39 +03:00
```python async
2021-01-16 03:01:41 +03:00
# Use a regular expression
2021-01-15 02:01:39 +03:00
async with page.expect_response(re.compile(r"\.jpeg$")) as response_info:
2022-10-04 03:02:46 +03:00
await page.get_by_text("Update").click()
2021-01-15 02:01:39 +03:00
response = await response_info.value
# Use a predicate taking a response object
async with page.expect_response(lambda response: token in response.url) as response_info:
2022-10-04 03:02:46 +03:00
await page.get_by_text("Update").click()
2021-01-15 02:01:39 +03:00
response = await response_info.value
```
```python sync
2021-01-16 03:01:41 +03:00
# Use a regular expression
2021-01-15 02:01:39 +03:00
with page.expect_response(re.compile(r"\.jpeg$")) as response_info:
2022-10-04 03:02:46 +03:00
page.get_by_text("Update").click()
2021-01-15 02:01:39 +03:00
response = response_info.value
2020-12-31 05:04:51 +03:00
2021-01-15 02:01:39 +03:00
# Use a predicate taking a response object
with page.expect_response(lambda response: token in response.url) as response_info:
2022-10-04 03:02:46 +03:00
page.get_by_text("Update").click()
2021-01-15 02:01:39 +03:00
response = response_info.value
```
2021-05-15 09:22:30 +03:00
```csharp
// Use a regular expression
2021-05-15 21:57:20 +03:00
var waitForResponseTask = page.WaitForResponseAsync(new Regex("\\.jpeg$"));
2022-10-04 03:02:46 +03:00
await page.GetByText("Update").ClickAsync();
2021-05-16 00:02:07 +03:00
var response = await waitForResponseTask;
2021-05-15 09:22:30 +03:00
// Use a predicate taking a Response object
2021-05-15 21:57:20 +03:00
var waitForResponseTask = page.WaitForResponseAsync(r => r.Url.Contains(token));
2022-10-04 03:02:46 +03:00
await page.GetByText("Update").ClickAsync();
2021-05-16 00:02:07 +03:00
var response = await waitForResponseTask;
2021-05-15 09:22:30 +03:00
```
2022-12-01 04:26:19 +03:00
2020-12-31 05:04:51 +03:00
## Handle requests
```js
await page.route('**/api/fetch_data', route => route.fulfill({
status: 200,
body: testData,
}));
await page.goto('https://example.com');
```
2021-03-01 20:18:44 +03:00
```java
page.route("**/api/fetch_data", route -> route.fulfill(new Route.FulfillOptions()
2021-03-06 00:50:34 +03:00
.setStatus(200)
.setBody(testData)));
2021-03-01 20:18:44 +03:00
page.navigate("https://example.com");
```
2021-01-15 02:01:39 +03:00
```python async
await page.route(
"**/api/fetch_data",
lambda route: route.fulfill(status=200, body=test_data))
await page.goto("https://example.com")
```
```python sync
page.route(
"**/api/fetch_data",
lambda route: route.fulfill(status=200, body=test_data))
page.goto("https://example.com")
```
2022-01-26 20:54:01 +03:00
You can mock API endpoints via handling the network requests in your Playwright script.
2020-12-31 05:04:51 +03:00
#### Variations
2022-09-29 16:42:01 +03:00
Set up route on the entire browser context with [`method: BrowserContext.route`] or page with [`method: Page.route`]. It will apply to popup windows and opened links.
2020-12-31 05:04:51 +03:00
2022-09-29 16:42:01 +03:00
```js
2020-12-31 05:04:51 +03:00
await browserContext.route('**/api/login', route => route.fulfill({
status: 200,
body: 'accept',
}));
await page.goto('https://example.com');
```
2021-03-01 20:18:44 +03:00
```java
browserContext.route("**/api/login", route -> route.fulfill(new Route.FulfillOptions()
2021-03-06 00:50:34 +03:00
.setStatus(200)
.setBody("accept")));
2021-03-01 20:18:44 +03:00
page.navigate("https://example.com");
```
2021-01-15 02:01:39 +03:00
```python async
await context.route(
"**/api/login",
lambda route: route.fulfill(status=200, body="accept"))
await page.goto("https://example.com")
```
```python sync
context.route(
"**/api/login",
lambda route: route.fulfill(status=200, body="accept"))
page.goto("https://example.com")
```
2020-12-31 05:04:51 +03:00
2021-05-15 09:22:30 +03:00
```csharp
await page.RouteAsync("**/api/fetch_data", async route => {
2022-12-01 04:26:19 +03:00
await route.FulfillAsync(new() { Status = 200, Body = testData });
2021-05-15 09:22:30 +03:00
});
await page.GotoAsync("https://example.com");
```
2020-12-31 05:04:51 +03:00
## Modify requests
```js
// Delete header
await page.route('**/*', route => {
const headers = route.request().headers();
delete headers['X-Secret'];
2022-12-23 12:57:29 +03:00
route.continue({ headers });
2020-12-31 05:04:51 +03:00
});
// Continue requests as POST.
2022-12-23 12:57:29 +03:00
await page.route('**/*', route => route.continue({ method: 'POST' }));
2020-12-31 05:04:51 +03:00
```
2021-03-01 20:18:44 +03:00
```java
// Delete header
page.route("**/*", route -> {
Map< String , String > headers = new HashMap< >(route.request().headers());
headers.remove("X-Secret");
2021-03-06 00:50:34 +03:00
route.resume(new Route.ResumeOptions().setHeaders(headers));
2021-03-01 20:18:44 +03:00
});
// Continue requests as POST.
2021-03-06 00:50:34 +03:00
page.route("**/*", route -> route.resume(new Route.ResumeOptions().setMethod("POST")));
2021-03-01 20:18:44 +03:00
```
2021-01-15 02:01:39 +03:00
```python async
# Delete header
async def handle_route(route):
headers = route.request.headers
del headers["x-secret"]
route.continue_(headers=headers)
await page.route("**/*", handle_route)
# Continue requests as POST.
await page.route("**/*", lambda route: route.continue_(method="POST"))
```
```python sync
# Delete header
def handle_route(route):
headers = route.request.headers
del headers["x-secret"]
route.continue_(headers=headers)
page.route("**/*", handle_route)
# Continue requests as POST.
page.route("**/*", lambda route: route.continue_(method="POST"))
```
2021-05-15 09:22:30 +03:00
```csharp
// Delete header
await page.RouteAsync("**/*", async route => {
var headers = new Dictionary< string , string > (route.Request.Headers.ToDictionary(x => x.Key, x => x.Value));
headers.Remove("X-Secret");
2021-05-20 03:19:25 +03:00
await route.ContinueAsync(new RouteContinueOptions { Headers = headers });
2021-05-15 09:22:30 +03:00
});
// Continue requests as POST.
2021-05-18 06:10:32 +03:00
await page.RouteAsync("**/*", async route => await route.ContinueAsync(method: "POST"));
2021-05-15 09:22:30 +03:00
```
2020-12-31 05:04:51 +03:00
You can continue requests with modifications. Example above removes an HTTP header from the outgoing requests.
## Abort requests
2022-09-29 16:42:01 +03:00
You can abort requests using [`method: Page.route`] and [`method: Route.abort`].
2020-12-31 05:04:51 +03:00
```js
await page.route('**/*.{png,jpg,jpeg}', route => route.abort());
// Abort based on the request type
await page.route('**/*', route => {
return route.request().resourceType() === 'image' ?
route.abort() : route.continue();
});
```
2021-03-01 20:18:44 +03:00
```java
page.route("**/*.{png,jpg,jpeg}", route -> route.abort());
// Abort based on the request type
page.route("**/*", route -> {
if ("image".equals(route.request().resourceType()))
route.abort();
else
route.resume();
});
```
2021-01-15 02:01:39 +03:00
```python async
await page.route("**/*.{png,jpg,jpeg}", lambda route: route.abort())
2020-12-31 05:04:51 +03:00
2021-01-15 02:01:39 +03:00
# Abort based on the request type
await page.route("**/*", lambda route: route.abort() if route.request.resource_type == "image" else route.continue_())
```
```python sync
page.route("**/*.{png,jpg,jpeg}", lambda route: route.abort())
# Abort based on the request type
page.route("**/*", lambda route: route.abort() if route.request.resource_type == "image" else route.continue_())
```
2021-05-15 09:22:30 +03:00
```csharp
await page.RouteAsync("**/*.{png,jpg,jpeg}", route => route.AbortAsync());
// Abort based on the request type
await page.RouteAsync("**/*", async route => {
if ("image".Equals(route.Request.ResourceType))
await route.AbortAsync();
else
2021-05-18 06:10:32 +03:00
await route.ContinueAsync();
2021-05-15 09:22:30 +03:00
});
```
2021-10-19 03:53:06 +03:00
## Modify responses
2022-09-29 16:42:01 +03:00
To modify a response use [APIRequestContext] to get the original response and then pass the response to [`method: Route.fulfill`]. You can override individual fields on the response via options:
2021-10-19 03:53:06 +03:00
```js
await page.route('**/title.html', async route => {
// Fetch original response.
2023-01-11 20:15:21 +03:00
const response = await route.fetch();
2021-10-19 03:53:06 +03:00
// Add a prefix to the title.
let body = await response.text();
body = body.replace('< title > ', '< title > My prefix:');
route.fulfill({
// Pass all fields from the response.
response,
// Override response body.
body,
// Force content type to be html.
headers: {
...response.headers(),
'content-type': 'text/html'
}
});
});
```
2022-06-03 00:12:09 +03:00
```java
page.route("**/title.html", route -> {
// Fetch original response.
2023-01-11 20:15:21 +03:00
APIResponse response = route.fetch();
2022-06-03 00:12:09 +03:00
// Add a prefix to the title.
String body = response.text();
body = body.replace("< title > ", "< title > My prefix:");
Map< String , String > headers = response.headers();
headers.put("content-type": "text/html");
route.fulfill(new Route.FulfillOptions()
// Pass all fields from the response.
.setResponse(response)
// Override response body.
.setBody(body)
// Force content type to be html.
.setHeaders(headers));
});
```
```python async
async def handle_route(route: Route) -> None:
# Fetch original response.
2023-01-11 20:15:21 +03:00
response = await route.fetch()
2022-06-03 00:12:09 +03:00
# Add a prefix to the title.
body = await response.text()
body = body.replace("< title > ", "< title > My prefix:")
await route.fulfill(
# Pass all fields from the response.
response=response,
# Override response body.
body=body,
# Force content type to be html.
headers={**response.headers, "content-type": "text/html"},
)
await page.route("**/title.html", handle_route)
```
```python sync
def handle_route(route: Route) -> None:
# Fetch original response.
2023-01-11 20:15:21 +03:00
response = route.fetch()
2022-06-03 00:12:09 +03:00
# Add a prefix to the title.
body = response.text()
body = body.replace("< title > ", "< title > My prefix:")
route.fulfill(
# Pass all fields from the response.
response=response,
# Override response body.
body=body,
# Force content type to be html.
headers={**response.headers, "content-type": "text/html"},
)
page.route("**/title.html", handle_route)
```
```csharp
await Page.RouteAsync("**/title.html", async route =>
{
// Fetch original response.
2023-01-11 20:15:21 +03:00
var response = await route.FetchAsync();
2022-06-03 00:12:09 +03:00
// Add a prefix to the title.
var body = await response.TextAsync();
body = body.Replace("< title > ", "< title > My prefix:");
var headers = response.Headers;
headers.Add("Content-Type", "text/html");
await route.FulfillAsync(new()
{
// Pass all fields from the response.
Response = response,
// Override response body.
Body = body,
// Force content type to be html.
Headers = headers,
});
});
```
2022-06-11 01:32:03 +03:00
## Record and replay requests
You can record network activity as an HTTP Archive file (HAR). Later on, this archive can be used to mock responses to the network requests. You'll need to:
1. Record a HAR file.
1. Commit the HAR file alongside the tests.
1. Route requests using the saved HAR files in the tests.
### Recording HAR with CLI
2022-06-21 03:54:39 +03:00
Open the browser with [Playwright CLI ](./cli.md ) and pass `--save-har` option to produce a HAR file. Optionally, use `--save-har-glob` to only save requests you are interested in, for example API endpoints. If the har file name ends with `.zip` , artifacts are written as separate files and are all compressed into a single `zip` .
2022-06-11 01:32:03 +03:00
```bash js
# Save API requests from example.com as "example.har" archive.
npx playwright open --save-har=example.har --save-har-glob="**/api/**" https://example.com
```
```bash java
# Save API requests from example.com as "example.har" archive.
2023-01-05 21:55:07 +03:00
mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI -D exec.args="open --save-har=example.har --save-har-glob='**/api/**' https://example.com"
2022-06-11 01:32:03 +03:00
```
```bash python
# Save API requests from example.com as "example.har" archive.
playwright open --save-har=example.har --save-har-glob="**/api/**" https://example.coms
```
```bash csharp
# Save API requests from example.com as "example.har" archive.
2022-08-14 21:01:00 +03:00
pwsh bin/Debug/netX/playwright.ps1 open --save-har=example.har --save-har-glob="**/api/**" https://example.com
2022-06-11 01:32:03 +03:00
```
### Recording HAR with a script
2022-06-21 03:54:39 +03:00
Alternatively, instead of using the CLI, you can record HAR programmatically. Pass [`option: har`] option when creating a [BrowserContext] with [`method: Browser.newContext`] to create an archive. If the har file name ends with `.zip` , artifacts are written as separate files and are all compressed into a single `zip` .
2022-06-11 01:32:03 +03:00
```js
const context = await browser.newContext({
recordHar: { path: 'example.har', urlFilter: '**/api/**' }
});
// ... Perform actions ...
// Close context to ensure HAR is saved to disk.
await context.close();
```
```java
BrowserContext context = browser.newContext(new Browser.NewContextOptions()
.setRecordHarPath(Paths.get("example.har"))
2022-06-28 06:34:30 +03:00
.setRecordHarUrlFilter("**/api/**"));
2022-06-11 01:32:03 +03:00
// ... Perform actions ...
// Close context to ensure HAR is saved to disk.
context.close();
```
```python async
context = await browser.new_context(record_har_path="example.har", record_har_url_filter="**/api/**")
# ... Perform actions ...
# Close context to ensure HAR is saved to disk.
await context.close()
```
```python sync
context = browser.new_context(record_har_path="example.har", record_har_url_filter="**/api/**")
# ... Perform actions ...
# Close context to ensure HAR is saved to disk.
context.close()
```
```csharp
2022-07-13 12:50:18 +03:00
var context = await browser.NewContextAsync(new() {
2022-06-11 01:32:03 +03:00
RecordHarPath = "example.har",
RecordHarUrlFilter = "**/api/**",
});
// ... Perform actions ...
// Close context to ensure HAR is saved to disk.
await context.CloseAsync();
```
### Replaying from HAR
2022-06-22 08:12:37 +03:00
Use [`method: Page.routeFromHAR`] or [`method: BrowserContext.routeFromHAR`] to serve matching responses from the [HAR ](http://www.softwareishard.com/blog/har-12-spec/ ) file.
2022-06-11 01:32:03 +03:00
```js
// Replay API requests from HAR.
2022-06-15 19:33:19 +03:00
// Either use a matching response from the HAR,
// or abort the request if nothing matches.
2022-06-22 08:12:37 +03:00
await page.routeFromHAR('example.har');
2022-06-11 01:32:03 +03:00
```
```java
2022-06-15 19:33:19 +03:00
// Either use a matching response from the HAR,
// or abort the request if nothing matches.
2022-06-22 08:12:37 +03:00
page.routeFromHAR(Paths.get("example.har"));
2022-06-11 01:32:03 +03:00
```
```python async
2022-06-15 19:33:19 +03:00
# Either use a matching response from the HAR,
# or abort the request if nothing matches.
2022-06-28 06:34:30 +03:00
await page.route_from_har("example.har")
2022-06-11 01:32:03 +03:00
```
```python sync
2022-06-15 19:33:19 +03:00
# Either use a matching response from the HAR,
# or abort the request if nothing matches.
2022-06-28 06:34:30 +03:00
page.route_from_har("example.har")
2022-06-11 01:32:03 +03:00
```
```csharp
2022-06-15 19:33:19 +03:00
// Either use a matching response from the HAR,
// or abort the request if nothing matches.
2022-06-22 08:12:37 +03:00
await context.RouteFromHARAsync("example.har");
2022-06-11 01:32:03 +03:00
```
2022-06-21 03:54:39 +03:00
HAR replay matches URL and HTTP method strictly. For POST requests, it also matches POST payloads strictly. If multiple recordings match a request, the one with the most matching headers is picked. An entry resulting in a redirect will be followed automatically.
Similar to when recording, if given HAR file name ends with `.zip` , it is considered an archive containing the HAR file along with network payloads stored as separate entries. You can also extract this archive, edit payloads or HAR log manually and point to the extracted har file. All the payloads will be resolved relative to the extracted har file on the file system.
2021-03-24 03:17:59 +03:00
## WebSockets
2022-09-29 16:42:01 +03:00
Playwright supports [WebSockets ](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API ) inspection out of the box. Every time a WebSocket is created, the [`event: Page.webSocket`] event is fired. This event contains the [WebSocket] instance for further web socket frames inspection:
2021-03-24 03:17:59 +03:00
```js
page.on('websocket', ws => {
console.log(`WebSocket opened: ${ws.url()}>`);
ws.on('framesent', event => console.log(event.payload));
ws.on('framereceived', event => console.log(event.payload));
ws.on('close', () => console.log('WebSocket closed'));
});
```
```java
page.onWebSocket(ws -> {
log("WebSocket opened: " + ws.url());
ws.onFrameSent(frameData -> log(frameData.text()));
ws.onFrameReceived(frameData -> log(frameData.text()));
ws.onClose(ws1 -> log("WebSocket closed"));
});
```
```python
def on_web_socket(ws):
print(f"WebSocket opened: {ws.url}")
ws.on("framesent", lambda payload: print(payload))
ws.on("framereceived", lambda payload: print(payload))
ws.on("close", lambda payload: print("WebSocket closed"))
page.on("websocket", on_web_socket)
```
2021-05-15 09:22:30 +03:00
```csharp
2021-05-15 21:57:20 +03:00
page.WebSocket += (_, ws) =>
{
2021-05-15 09:22:30 +03:00
Console.WriteLine("WebSocket opened: " + ws.Url);
ws.FrameSent += (_, f) => Console.WriteLine(f.Text);
ws.FrameReceived += (_, f) => Console.WriteLine(f.Text);
ws.Close += (_, ws1) => Console.WriteLine("WebSocket closed");
};
```
2022-07-15 03:40:22 +03:00
## Missing Network Events and Service Workers
Playwright's built-in [`method: BrowserContext.route`] and [`method: Page.route`] allow your tests to natively route requests and perform mocking and interception.
1. If you're using Playwright's native [`method: BrowserContext.route`] and [`method: Page.route`], and it appears network events are missing, disable Service Workers by setting [`option: Browser.newContext.serviceWorkers`] to `'block'` .
1. It might be that you are using a mock tool such as Mock Service Worker (MSW). While this tool works out of the box for mocking responses, it adds its own Service Worker that takes over the network requests, hence making them invisible to [`method: BrowserContext.route`] and [`method: Page.route`]. If you are interested in both network testing and mocking, consider using built-in [`method: BrowserContext.route`] and [`method: Page.route`] for [response mocking ](#handle-requests ).
1. If you're interested in not solely using Service Workers for testing and network mocking, but in routing and listening for requests made by Service Workers themselves, please see [this experimental feature ](https://github.com/microsoft/playwright/issues/15684 ).