Skip to main content

Network

Introduction

Playwright provides APIs to monitor and modify browser network traffic, both HTTP and HTTPS. Any requests that a page does, including XHRs and fetch requests, can be tracked, modified and handled.

Mock APIs

Check out our API mocking guide to learn more on how to

  • mock API requests and never hit the API
  • perform the API request and modify the response
  • use HAR files to mock network requests.

HTTP Authentication

Perform HTTP Authentication.

using var context = await Browser.NewContextAsync(new()
{
HttpCredentials = new HttpCredentials
{
Username = "bill",
Password = "pa55w0rd"
},
});
var page = await context.NewPageAsync();
await page.GotoAsync("https://example.com");

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:

var proxy = new Proxy
{
Server = "http://myproxy.com:3128",
Username = "user",
Password = "pwd"
};
await using var browser = await BrowserType.LaunchAsync(new()
{
Proxy = proxy
});

Its also possible to specify it per context:

await using var browser = await BrowserType.LaunchAsync();
await using var context = await browser.NewContextAsync(new()
{
Proxy = new Proxy { Server = "http://myproxy.com:3128" },
});

Network events

You can monitor all the Requests and Responses:

using Microsoft.Playwright;

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");

Or wait for a network response after the button click with Page.RunAndWaitForResponseAsync():

// Use a glob URL pattern
var waitForResponseTask = page.WaitForResponseAsync("**/api/fetch_data");
await page.GetByText("Update").ClickAsync();
var response = await waitForResponseTask;

Variations

Wait for Responses with Page.RunAndWaitForResponseAsync()

// Use a regular expression
var waitForResponseTask = page.WaitForResponseAsync(new Regex("\\.jpeg$"));
await page.GetByText("Update").ClickAsync();
var response = await waitForResponseTask;

// Use a predicate taking a Response object
var waitForResponseTask = page.WaitForResponseAsync(r => r.Url.Contains(token));
await page.GetByText("Update").ClickAsync();
var response = await waitForResponseTask;

Handle requests

You can mock API endpoints via handling the network requests in your Playwright script.

Variations

Set up route on the entire browser context with BrowserContext.RouteAsync() or page with Page.RouteAsync(). It will apply to popup windows and opened links.

await page.RouteAsync("**/api/fetch_data", async route => {
await route.FulfillAsync(new() { Status = 200, Body = testData });
});
await page.GotoAsync("https://example.com");

Modify requests

// 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");
await route.ContinueAsync(new() { Headers = headers });
});

// Continue requests as POST.
await Page.RouteAsync("**/*", async route => await route.ContinueAsync(new() { Method = "POST" }));

You can continue requests with modifications. Example above removes an HTTP header from the outgoing requests.

Abort requests

You can abort requests using Page.RouteAsync() and Route.AbortAsync().

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
await route.ContinueAsync();
});

Modify responses

To modify a response use APIRequestContext to get the original response and then pass the response to Route.FulfillAsync(). You can override individual fields on the response via options:

await Page.RouteAsync("**/title.html", async route =>
{
// Fetch original response.
var response = await route.FetchAsync();
// 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,
});
});

Glob URL patterns

Playwright uses simplified glob patterns for URL matching in network interception methods like Page.RouteAsync() or Page.RunAndWaitForResponseAsync(). These patterns support basic wildcards:

  1. Asterisks:
    • A single * matches any characters except /
    • A double ** matches any characters including /
  2. Question mark ? matches any single character except /
  3. Curly braces {} can be used to match a list of options separated by commas ,

Examples:

  • https://example.com/*.js matches https://example.com/file.js but not https://example.com/path/file.js
  • **/*.js matches both https://example.com/file.js and https://example.com/path/file.js
  • **/*.{png,jpg,jpeg} matches all image requests

Important notes:

  • The glob pattern must match the entire URL, not just a part of it.
  • When using globs for URL matching, consider the full URL structure, including the protocol and path separators.
  • For more complex matching requirements, consider using [RegExp] instead of glob patterns.

WebSockets

Playwright supports WebSockets inspection, mocking and modifying out of the box. See our API mocking guide to learn how to mock WebSockets.

Every time a WebSocket is created, the Page.WebSocket event is fired. This event contains the WebSocket instance for further web socket frames inspection:

page.WebSocket += (_, ws) =>
{
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");
};

Missing Network Events and Service Workers

Playwright's built-in BrowserContext.RouteAsync() and Page.RouteAsync() allow your tests to natively route requests and perform mocking and interception.

  1. If you're using Playwright's native BrowserContext.RouteAsync() and Page.RouteAsync(), and it appears network events are missing, disable Service Workers by setting ServiceWorkers to 'block'.
  2. 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 BrowserContext.RouteAsync() and Page.RouteAsync(). If you are interested in both network testing and mocking, consider using built-in BrowserContext.RouteAsync() and Page.RouteAsync() for response mocking.
  3. 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.