Table of Contents

Interface IBrowserContext

Namespace
Microsoft.Playwright
Assembly
Microsoft.Playwright.dll

BrowserContexts provide a way to operate multiple independent browser sessions.

If a page opens another page, e.g. with a window.open call, the popup will belong to the parent page's browser context.

Playwright allows creating "incognito" browser contexts with NewContextAsync(BrowserNewContextOptions?) method. "Incognito" browser contexts don't write any browsing data to disk.

using var playwright = await Playwright.CreateAsync();
var browser = await playwright.Firefox.LaunchAsync(new() { Headless = false });
// Create a new incognito browser context
var context = await browser.NewContextAsync();
// Create a new page inside context.
var page = await context.NewPageAsync();
await page.GotoAsync("https://bing.com");
// Dispose context once it is no longer needed.
await context.CloseAsync();
public interface IBrowserContext : IAsyncDisposable

Properties

APIRequest

API testing helper associated with this context. Requests made with this API will use context cookies.

IAPIRequestContext APIRequest { get; }

Property Value

IAPIRequestContext

BackgroundPages

All existing background pages in the context.

IReadOnlyList<IPage> BackgroundPages { get; }

Property Value

IReadOnlyList<IPage>

Remarks

Background pages are only supported on Chromium-based browsers.

Browser

Returns the browser instance of the context. If it was launched as a persistent context null gets returned.

IBrowser? Browser { get; }

Property Value

IBrowser

Clock

Playwright has ability to mock clock and passage of time.

IClock Clock { get; }

Property Value

IClock

Pages

Returns all open pages in the context.

IReadOnlyList<IPage> Pages { get; }

Property Value

IReadOnlyList<IPage>

Tracing

ITracing Tracing { get; }

Property Value

ITracing

Methods

Adds cookies into this browser context. All pages within this context will have these cookies installed. Cookies can be obtained via CookiesAsync(IEnumerable<string>?).

**Usage**

await context.AddCookiesAsync(new[] { cookie1, cookie2 });
Task AddCookiesAsync(IEnumerable<Cookie> cookies)

Parameters

cookies IEnumerable<Cookie>

Adds cookies to the browser context. For the cookie to apply to all subdomains as well, prefix domain with a dot, like this: ".example.com".

Returns

Task

AddInitScriptAsync(string?, string?)

Adds a script which would be evaluated in one of the following scenarios:

  • Whenever a page is created in the browser context or is navigated.
  • Whenever a child frame is attached or navigated in any page in the browser context. In this case, the script is evaluated in the context of the newly attached frame.

The script is evaluated after the document was created but before any of its scripts were run. This is useful to amend the JavaScript environment, e.g. to seed Math.random.

**Usage**

An example of overriding Math.random before the page loads:

await Context.AddInitScriptAsync(scriptPath: "preload.js");
Task AddInitScriptAsync(string? script = null, string? scriptPath = null)

Parameters

script string

Script to be evaluated in all pages in the browser context.

scriptPath string

Instead of specifying script, gives the file name to load from.

Returns

Task

Remarks

The order of evaluation of multiple scripts installed via AddInitScriptAsync(string?, string?) and AddInitScriptAsync(string?, string?) is not defined.

ClearCookiesAsync(BrowserContextClearCookiesOptions?)

Removes cookies from context. Accepts optional filter.

**Usage**

await context.ClearCookiesAsync();
await context.ClearCookiesAsync(new() { Name = "session-id" });
await context.ClearCookiesAsync(new() { Domain = "my-origin.com" });
await context.ClearCookiesAsync(new() { Path = "/api/v1" });
await context.ClearCookiesAsync(new() { Name = "session-id", Domain = "my-origin.com" });
Task ClearCookiesAsync(BrowserContextClearCookiesOptions? options = null)

Parameters

options BrowserContextClearCookiesOptions

Call options

Returns

Task

ClearPermissionsAsync()

Clears all permission overrides for the browser context.

**Usage**

var context = await browser.NewContextAsync();
await context.GrantPermissionsAsync(new[] { "clipboard-read" });
// Alternatively, you can use the helper class ContextPermissions
//  to specify the permissions...
// do stuff ...
await context.ClearPermissionsAsync();
Task ClearPermissionsAsync()

Returns

Task

CloseAsync(BrowserContextCloseOptions?)

Closes the browser context. All the pages that belong to the browser context will be closed.

Task CloseAsync(BrowserContextCloseOptions? options = null)

Parameters

options BrowserContextCloseOptions

Call options

Returns

Task

Remarks

The default browser context cannot be closed.

CookiesAsync(IEnumerable<string>?)

If no URLs are specified, this method returns all cookies. If URLs are specified, only cookies that affect those URLs are returned.

Task<IReadOnlyList<BrowserContextCookiesResult>> CookiesAsync(IEnumerable<string>? urls = null)

Parameters

urls IEnumerable<string>

Optional list of URLs.

Returns

Task<IReadOnlyList<BrowserContextCookiesResult>>

ExposeBindingAsync(string, Action, BrowserContextExposeBindingOptions?)

The method adds a function called name on the window object of every frame in every page in the context. When called, the function executes callback and returns a Task which resolves to the return value of callback. If the callback returns a , it will be awaited.

The first argument of the callback function contains information about the caller: { browserContext: BrowserContext, page: Page, frame: Frame }.

See ExposeBindingAsync(string, Action, PageExposeBindingOptions?) for page-only version.

**Usage**

An example of exposing page URL to all frames in all pages in the context:

using Microsoft.Playwright;

using var playwright = await Playwright.CreateAsync(); var browser = await playwright.Webkit.LaunchAsync(new() { Headless = false }); var context = await browser.NewContextAsync();

await context.ExposeBindingAsync("pageURL", source => source.Page.Url); var page = await context.NewPageAsync(); await page.SetContentAsync("<script>\n" + " async function onClick() {\n" + " document.querySelector('div').textContent = await window.pageURL();\n" + " }\n" + "</script>\n" + "<button onclick="onClick()">Click me</button>\n" + "<div></div>"); await page.GetByRole(AriaRole.Button).ClickAsync();

Task ExposeBindingAsync(string name, Action callback, BrowserContextExposeBindingOptions? options = null)

Parameters

name string

Name of the function on the window object.

callback Action

Callback function that will be called in the Playwright's context.

options BrowserContextExposeBindingOptions

Call options

Returns

Task

ExposeBindingAsync(string, Action<BindingSource>)

Task ExposeBindingAsync(string name, Action<BindingSource> callback)

Parameters

name string
callback Action<BindingSource>

Returns

Task

ExposeBindingAsync<T>(string, Action<BindingSource, T>)

Task ExposeBindingAsync<T>(string name, Action<BindingSource, T> callback)

Parameters

name string
callback Action<BindingSource, T>

Returns

Task

Type Parameters

T

ExposeBindingAsync<TResult>(string, Func<BindingSource, IJSHandle, TResult>)

Task ExposeBindingAsync<TResult>(string name, Func<BindingSource, IJSHandle, TResult> callback)

Parameters

name string
callback Func<BindingSource, IJSHandle, TResult>

Returns

Task

Type Parameters

TResult

ExposeBindingAsync<TResult>(string, Func<BindingSource, TResult>)

Task ExposeBindingAsync<TResult>(string name, Func<BindingSource, TResult> callback)

Parameters

name string
callback Func<BindingSource, TResult>

Returns

Task

Type Parameters

TResult

ExposeBindingAsync<T, TResult>(string, Func<BindingSource, T, TResult>)

Task ExposeBindingAsync<T, TResult>(string name, Func<BindingSource, T, TResult> callback)

Parameters

name string
callback Func<BindingSource, T, TResult>

Returns

Task

Type Parameters

T
TResult

ExposeBindingAsync<T1, T2, TResult>(string, Func<BindingSource, T1, T2, TResult>)

Task ExposeBindingAsync<T1, T2, TResult>(string name, Func<BindingSource, T1, T2, TResult> callback)

Parameters

name string
callback Func<BindingSource, T1, T2, TResult>

Returns

Task

Type Parameters

T1
T2
TResult

ExposeBindingAsync<T1, T2, T3, TResult>(string, Func<BindingSource, T1, T2, T3, TResult>)

Task ExposeBindingAsync<T1, T2, T3, TResult>(string name, Func<BindingSource, T1, T2, T3, TResult> callback)

Parameters

name string
callback Func<BindingSource, T1, T2, T3, TResult>

Returns

Task

Type Parameters

T1
T2
T3
TResult

ExposeBindingAsync<T1, T2, T3, T4, TResult>(string, Func<BindingSource, T1, T2, T3, T4, TResult>)

Task ExposeBindingAsync<T1, T2, T3, T4, TResult>(string name, Func<BindingSource, T1, T2, T3, T4, TResult> callback)

Parameters

name string
callback Func<BindingSource, T1, T2, T3, T4, TResult>

Returns

Task

Type Parameters

T1
T2
T3
T4
TResult

ExposeFunctionAsync(string, Action)

The method adds a function called name on the window object of every frame in every page in the context. When called, the function executes callback and returns a Task which resolves to the return value of callback.

If the callback returns a Task, it will be awaited.

See ExposeFunctionAsync(string, Action) for page-only version.

**Usage**

An example of adding a sha256 function to all pages in the context:

using Microsoft.Playwright;
using System;
using System.Security.Cryptography;
using System.Threading.Tasks;

class BrowserContextExamples { public static async Task Main() { using var playwright = await Playwright.CreateAsync(); var browser = await playwright.Webkit.LaunchAsync(new() { Headless = false }); var context = await browser.NewContextAsync();

    await context.ExposeFunctionAsync("sha256", (string input) =>
    {
        return Convert.ToBase64String(
            SHA256.Create().ComputeHash(System.Text.Encoding.UTF8.GetBytes(input)));
    });

    var page = await context.NewPageAsync();
    await page.SetContentAsync("<script>\n" +
    "  async function onClick() {\n" +
    "    document.querySelector('div').textContent = await window.sha256('PLAYWRIGHT');\n" +
    "  }\n" +
    "</script>\n" +
    "<button onclick=\"onClick()\">Click me</button>\n" +
    "<div></div>");

    await page.GetByRole(AriaRole.Button).ClickAsync();
    Console.WriteLine(await page.TextContentAsync("div"));
}

}

Task ExposeFunctionAsync(string name, Action callback)

Parameters

name string

Name of the function on the window object.

callback Action

Callback function that will be called in the Playwright's context.

Returns

Task

ExposeFunctionAsync<T>(string, Action<T>)

Task ExposeFunctionAsync<T>(string name, Action<T> callback)

Parameters

name string
callback Action<T>

Returns

Task

Type Parameters

T

ExposeFunctionAsync<TResult>(string, Func<TResult>)

Task ExposeFunctionAsync<TResult>(string name, Func<TResult> callback)

Parameters

name string
callback Func<TResult>

Returns

Task

Type Parameters

TResult

ExposeFunctionAsync<T, TResult>(string, Func<T, TResult>)

Task ExposeFunctionAsync<T, TResult>(string name, Func<T, TResult> callback)

Parameters

name string
callback Func<T, TResult>

Returns

Task

Type Parameters

T
TResult

ExposeFunctionAsync<T1, T2, TResult>(string, Func<T1, T2, TResult>)

Task ExposeFunctionAsync<T1, T2, TResult>(string name, Func<T1, T2, TResult> callback)

Parameters

name string
callback Func<T1, T2, TResult>

Returns

Task

Type Parameters

T1
T2
TResult

ExposeFunctionAsync<T1, T2, T3, TResult>(string, Func<T1, T2, T3, TResult>)

Task ExposeFunctionAsync<T1, T2, T3, TResult>(string name, Func<T1, T2, T3, TResult> callback)

Parameters

name string
callback Func<T1, T2, T3, TResult>

Returns

Task

Type Parameters

T1
T2
T3
TResult

ExposeFunctionAsync<T1, T2, T3, T4, TResult>(string, Func<T1, T2, T3, T4, TResult>)

Task ExposeFunctionAsync<T1, T2, T3, T4, TResult>(string name, Func<T1, T2, T3, T4, TResult> callback)

Parameters

name string
callback Func<T1, T2, T3, T4, TResult>

Returns

Task

Type Parameters

T1
T2
T3
T4
TResult

GrantPermissionsAsync(IEnumerable<string>, BrowserContextGrantPermissionsOptions?)

Grants specified permissions to the browser context. Only grants corresponding permissions to the given origin if specified.

Task GrantPermissionsAsync(IEnumerable<string> permissions, BrowserContextGrantPermissionsOptions? options = null)

Parameters

permissions IEnumerable<string>

A permission or an array of permissions to grant. Permissions can be one of the following values:

  • 'accelerometer'
  • 'accessibility-events'
  • 'ambient-light-sensor'
  • 'background-sync'
  • 'camera'
  • 'clipboard-read'
  • 'clipboard-write'
  • 'geolocation'
  • 'gyroscope'
  • 'magnetometer'
  • 'microphone'
  • 'midi-sysex' (system-exclusive midi)
  • 'midi'
  • 'notifications'
  • 'payment-handler'
  • 'storage-access'
options BrowserContextGrantPermissionsOptions

Call options

Returns

Task

NewCDPSessionAsync(IFrame)

Returns the newly created session.

Task<ICDPSession> NewCDPSessionAsync(IFrame page)

Parameters

page IFrame

Target to create new session for. For backwards-compatibility, this parameter is named page, but it can be a Page or Frame type.

Returns

Task<ICDPSession>

Remarks

CDP sessions are only supported on Chromium-based browsers.

NewCDPSessionAsync(IPage)

Returns the newly created session.

Task<ICDPSession> NewCDPSessionAsync(IPage page)

Parameters

page IPage

Target to create new session for. For backwards-compatibility, this parameter is named page, but it can be a Page or Frame type.

Returns

Task<ICDPSession>

Remarks

CDP sessions are only supported on Chromium-based browsers.

NewPageAsync()

Creates a new page in the browser context.

Task<IPage> NewPageAsync()

Returns

Task<IPage>

RouteAsync(Func<string, bool>, Action<IRoute>, BrowserContextRouteOptions?)

Routing provides the capability to modify network requests that are made by any page in the browser context. Once route is enabled, every request matching the url pattern will stall unless it's continued, fulfilled or aborted.

**Usage**

An example of a naive handler that aborts all image requests:

var context = await browser.NewContextAsync();
var page = await context.NewPageAsync();
await context.RouteAsync("**/*.{png,jpg,jpeg}", r => r.AbortAsync());
await page.GotoAsync("https://theverge.com");
await browser.CloseAsync();

or the same snippet using a regex pattern instead:

var context = await browser.NewContextAsync();
var page = await context.NewPageAsync();
await context.RouteAsync(new Regex("(\\.png$)|(\\.jpg$)"), r => r.AbortAsync());
await page.GotoAsync("https://theverge.com");
await browser.CloseAsync();

It is possible to examine the request to decide the route action. For example, mocking all requests that contain some post data, and leaving all other requests as is:

await page.RouteAsync("/api/**", async r =>
{
    if (r.Request.PostData.Contains("my-string"))
        await r.FulfillAsync(new() { Body = "mocked-data" });
    else
        await r.ContinueAsync();
});

Page routes (set up with RouteAsync(string, Action<IRoute>, PageRouteOptions?)) take precedence over browser context routes when request matches both handlers.

To remove a route with its handler you can use UnrouteAsync(string, Action<IRoute>?).

Task RouteAsync(Func<string, bool> url, Action<IRoute> handler, BrowserContextRouteOptions? options = null)

Parameters

url Func<string, bool>

A glob pattern, regex pattern or predicate receiving to match while routing. When a baseURL via the context options was provided and the passed URL is a path, it gets merged via the new URL() constructor.

handler Action<IRoute>

handler function to route the request.

options BrowserContextRouteOptions

Call options

Returns

Task

Remarks

RouteAsync(string, Action<IRoute>, BrowserContextRouteOptions?) will not intercept requests intercepted by Service Worker. See this issue. We recommend disabling Service Workers when using request interception by setting Browser.newContext.serviceWorkers.newContext.serviceWorkers to 'block'.

Enabling routing disables http cache.

RouteAsync(Func<string, bool>, Func<IRoute, Task>, BrowserContextRouteOptions?)

Task RouteAsync(Func<string, bool> url, Func<IRoute, Task> handler, BrowserContextRouteOptions? options = null)

Parameters

url Func<string, bool>
handler Func<IRoute, Task>
options BrowserContextRouteOptions

Returns

Task

RouteAsync(string, Action<IRoute>, BrowserContextRouteOptions?)

Routing provides the capability to modify network requests that are made by any page in the browser context. Once route is enabled, every request matching the url pattern will stall unless it's continued, fulfilled or aborted.

**Usage**

An example of a naive handler that aborts all image requests:

var context = await browser.NewContextAsync();
var page = await context.NewPageAsync();
await context.RouteAsync("**/*.{png,jpg,jpeg}", r => r.AbortAsync());
await page.GotoAsync("https://theverge.com");
await browser.CloseAsync();

or the same snippet using a regex pattern instead:

var context = await browser.NewContextAsync();
var page = await context.NewPageAsync();
await context.RouteAsync(new Regex("(\\.png$)|(\\.jpg$)"), r => r.AbortAsync());
await page.GotoAsync("https://theverge.com");
await browser.CloseAsync();

It is possible to examine the request to decide the route action. For example, mocking all requests that contain some post data, and leaving all other requests as is:

await page.RouteAsync("/api/**", async r =>
{
    if (r.Request.PostData.Contains("my-string"))
        await r.FulfillAsync(new() { Body = "mocked-data" });
    else
        await r.ContinueAsync();
});

Page routes (set up with RouteAsync(string, Action<IRoute>, PageRouteOptions?)) take precedence over browser context routes when request matches both handlers.

To remove a route with its handler you can use UnrouteAsync(string, Action<IRoute>?).

Task RouteAsync(string url, Action<IRoute> handler, BrowserContextRouteOptions? options = null)

Parameters

url string

A glob pattern, regex pattern or predicate receiving to match while routing. When a baseURL via the context options was provided and the passed URL is a path, it gets merged via the new URL() constructor.

handler Action<IRoute>

handler function to route the request.

options BrowserContextRouteOptions

Call options

Returns

Task

Remarks

RouteAsync(string, Action<IRoute>, BrowserContextRouteOptions?) will not intercept requests intercepted by Service Worker. See this issue. We recommend disabling Service Workers when using request interception by setting Browser.newContext.serviceWorkers.newContext.serviceWorkers to 'block'.

Enabling routing disables http cache.

RouteAsync(string, Func<IRoute, Task>, BrowserContextRouteOptions?)

Task RouteAsync(string url, Func<IRoute, Task> handler, BrowserContextRouteOptions? options = null)

Parameters

url string
handler Func<IRoute, Task>
options BrowserContextRouteOptions

Returns

Task

RouteAsync(Regex, Action<IRoute>, BrowserContextRouteOptions?)

Routing provides the capability to modify network requests that are made by any page in the browser context. Once route is enabled, every request matching the url pattern will stall unless it's continued, fulfilled or aborted.

**Usage**

An example of a naive handler that aborts all image requests:

var context = await browser.NewContextAsync();
var page = await context.NewPageAsync();
await context.RouteAsync("**/*.{png,jpg,jpeg}", r => r.AbortAsync());
await page.GotoAsync("https://theverge.com");
await browser.CloseAsync();

or the same snippet using a regex pattern instead:

var context = await browser.NewContextAsync();
var page = await context.NewPageAsync();
await context.RouteAsync(new Regex("(\\.png$)|(\\.jpg$)"), r => r.AbortAsync());
await page.GotoAsync("https://theverge.com");
await browser.CloseAsync();

It is possible to examine the request to decide the route action. For example, mocking all requests that contain some post data, and leaving all other requests as is:

await page.RouteAsync("/api/**", async r =>
{
    if (r.Request.PostData.Contains("my-string"))
        await r.FulfillAsync(new() { Body = "mocked-data" });
    else
        await r.ContinueAsync();
});

Page routes (set up with RouteAsync(string, Action<IRoute>, PageRouteOptions?)) take precedence over browser context routes when request matches both handlers.

To remove a route with its handler you can use UnrouteAsync(string, Action<IRoute>?).

Task RouteAsync(Regex url, Action<IRoute> handler, BrowserContextRouteOptions? options = null)

Parameters

url Regex

A glob pattern, regex pattern or predicate receiving to match while routing. When a baseURL via the context options was provided and the passed URL is a path, it gets merged via the new URL() constructor.

handler Action<IRoute>

handler function to route the request.

options BrowserContextRouteOptions

Call options

Returns

Task

Remarks

RouteAsync(string, Action<IRoute>, BrowserContextRouteOptions?) will not intercept requests intercepted by Service Worker. See this issue. We recommend disabling Service Workers when using request interception by setting Browser.newContext.serviceWorkers.newContext.serviceWorkers to 'block'.

Enabling routing disables http cache.

RouteAsync(Regex, Func<IRoute, Task>, BrowserContextRouteOptions?)

Task RouteAsync(Regex url, Func<IRoute, Task> handler, BrowserContextRouteOptions? options = null)

Parameters

url Regex
handler Func<IRoute, Task>
options BrowserContextRouteOptions

Returns

Task

RouteFromHARAsync(string, BrowserContextRouteFromHAROptions?)

If specified the network requests that are made in the context will be served from the HAR file. Read more about Replaying from HAR.

Playwright will not serve requests intercepted by Service Worker from the HAR file. See this issue. We recommend disabling Service Workers when using request interception by setting Browser.newContext.serviceWorkers.newContext.serviceWorkers to 'block'.

Task RouteFromHARAsync(string har, BrowserContextRouteFromHAROptions? options = null)

Parameters

har string

Path to a HAR file with prerecorded network data. If path is a relative path, then it is resolved relative to the current working directory.

options BrowserContextRouteFromHAROptions

Call options

Returns

Task

RunAndWaitForConsoleMessageAsync(Func<Task>, BrowserContextRunAndWaitForConsoleMessageOptions?)

Performs action and waits for a IConsoleMessage to be logged by in the pages in the context. If predicate is provided, it passes IConsoleMessage value into the predicate function and waits for predicate(message) to return a truthy value. Will throw an error if the page is closed before the Console event is fired.

Task<IConsoleMessage> RunAndWaitForConsoleMessageAsync(Func<Task> action, BrowserContextRunAndWaitForConsoleMessageOptions? options = null)

Parameters

action Func<Task>

Action that triggers the event.

options BrowserContextRunAndWaitForConsoleMessageOptions

Call options

Returns

Task<IConsoleMessage>

RunAndWaitForPageAsync(Func<Task>, BrowserContextRunAndWaitForPageOptions?)

Performs action and waits for a new IPage to be created in the context. If predicate is provided, it passes IPage value into the predicate function and waits for predicate(event) to return a truthy value. Will throw an error if the context closes before new IPage is created.

Task<IPage> RunAndWaitForPageAsync(Func<Task> action, BrowserContextRunAndWaitForPageOptions? options = null)

Parameters

action Func<Task>

Action that triggers the event.

options BrowserContextRunAndWaitForPageOptions

Call options

Returns

Task<IPage>

SetDefaultNavigationTimeout(float)

void SetDefaultNavigationTimeout(float timeout)

Parameters

timeout float

Maximum navigation time in milliseconds

Remarks

SetDefaultTimeout(float)

This setting will change the default maximum time for all the methods accepting timeout option.

void SetDefaultTimeout(float timeout)

Parameters

timeout float

Maximum time in milliseconds

Remarks

SetExtraHTTPHeadersAsync(IEnumerable<KeyValuePair<string, string>>)

The extra HTTP headers will be sent with every request initiated by any page in the context. These headers are merged with page-specific extra HTTP headers set with SetExtraHTTPHeadersAsync(IEnumerable<KeyValuePair<string, string>>). If page overrides a particular header, page-specific header value will be used instead of the browser context header value.

Task SetExtraHTTPHeadersAsync(IEnumerable<KeyValuePair<string, string>> headers)

Parameters

headers IEnumerable<KeyValuePair<string, string>>

An object containing additional HTTP headers to be sent with every request. All header values must be strings.

Returns

Task

Remarks

SetExtraHTTPHeadersAsync(IEnumerable<KeyValuePair<string, string>>) does not guarantee the order of headers in the outgoing requests.

SetGeolocationAsync(Geolocation?)

Sets the context's geolocation. Passing null or undefined emulates position unavailable.

**Usage**

await context.SetGeolocationAsync(new Geolocation()
{
    Latitude = 59.95f,
    Longitude = 30.31667f
});
Task SetGeolocationAsync(Geolocation? geolocation)

Parameters

geolocation Geolocation

Returns

Task

Remarks

Consider using GrantPermissionsAsync(IEnumerable<string>, BrowserContextGrantPermissionsOptions?) to grant permissions for the browser context pages to read its geolocation.

SetOfflineAsync(bool)

Task SetOfflineAsync(bool offline)

Parameters

offline bool

Whether to emulate network being offline for the browser context.

Returns

Task

StorageStateAsync(BrowserContextStorageStateOptions?)

Returns storage state for this browser context, contains current cookies and local storage snapshot.

Task<string> StorageStateAsync(BrowserContextStorageStateOptions? options = null)

Parameters

options BrowserContextStorageStateOptions

Call options

Returns

Task<string>

UnrouteAllAsync(BrowserContextUnrouteAllOptions?)

Task UnrouteAllAsync(BrowserContextUnrouteAllOptions? options = null)

Parameters

options BrowserContextUnrouteAllOptions

Call options

Returns

Task

UnrouteAsync(Func<string, bool>, Action<IRoute>?)

Removes a route created with RouteAsync(string, Action<IRoute>, BrowserContextRouteOptions?). When handler is not specified, removes all routes for the url.

Task UnrouteAsync(Func<string, bool> url, Action<IRoute>? handler = null)

Parameters

url Func<string, bool>

A glob pattern, regex pattern or predicate receiving used to register a routing with RouteAsync(string, Action<IRoute>, BrowserContextRouteOptions?).

handler Action<IRoute>

Optional handler function used to register a routing with RouteAsync(string, Action<IRoute>, BrowserContextRouteOptions?).

Returns

Task

UnrouteAsync(Func<string, bool>, Func<IRoute, Task>)

Task UnrouteAsync(Func<string, bool> url, Func<IRoute, Task> handler)

Parameters

url Func<string, bool>
handler Func<IRoute, Task>

Returns

Task

UnrouteAsync(string, Action<IRoute>?)

Removes a route created with RouteAsync(string, Action<IRoute>, BrowserContextRouteOptions?). When handler is not specified, removes all routes for the url.

Task UnrouteAsync(string url, Action<IRoute>? handler = null)

Parameters

url string

A glob pattern, regex pattern or predicate receiving used to register a routing with RouteAsync(string, Action<IRoute>, BrowserContextRouteOptions?).

handler Action<IRoute>

Optional handler function used to register a routing with RouteAsync(string, Action<IRoute>, BrowserContextRouteOptions?).

Returns

Task

UnrouteAsync(string, Func<IRoute, Task>)

Task UnrouteAsync(string url, Func<IRoute, Task> handler)

Parameters

url string
handler Func<IRoute, Task>

Returns

Task

UnrouteAsync(Regex, Action<IRoute>?)

Removes a route created with RouteAsync(string, Action<IRoute>, BrowserContextRouteOptions?). When handler is not specified, removes all routes for the url.

Task UnrouteAsync(Regex url, Action<IRoute>? handler = null)

Parameters

url Regex

A glob pattern, regex pattern or predicate receiving used to register a routing with RouteAsync(string, Action<IRoute>, BrowserContextRouteOptions?).

handler Action<IRoute>

Optional handler function used to register a routing with RouteAsync(string, Action<IRoute>, BrowserContextRouteOptions?).

Returns

Task

UnrouteAsync(Regex, Func<IRoute, Task>)

Task UnrouteAsync(Regex url, Func<IRoute, Task> handler)

Parameters

url Regex
handler Func<IRoute, Task>

Returns

Task

WaitForConsoleMessageAsync(BrowserContextWaitForConsoleMessageOptions?)

Performs action and waits for a IConsoleMessage to be logged by in the pages in the context. If predicate is provided, it passes IConsoleMessage value into the predicate function and waits for predicate(message) to return a truthy value. Will throw an error if the page is closed before the Console event is fired.

Task<IConsoleMessage> WaitForConsoleMessageAsync(BrowserContextWaitForConsoleMessageOptions? options = null)

Parameters

options BrowserContextWaitForConsoleMessageOptions

Call options

Returns

Task<IConsoleMessage>

WaitForPageAsync(BrowserContextWaitForPageOptions?)

Performs action and waits for a new IPage to be created in the context. If predicate is provided, it passes IPage value into the predicate function and waits for predicate(event) to return a truthy value. Will throw an error if the context closes before new IPage is created.

Task<IPage> WaitForPageAsync(BrowserContextWaitForPageOptions? options = null)

Parameters

options BrowserContextWaitForPageOptions

Call options

Returns

Task<IPage>

Events

BackgroundPage

Emitted when new background page is created in the context.

context.BackgroundPage += (_, backgroundPage) =>
{
    Console.WriteLine(backgroundPage.Url);
};
event EventHandler<IPage> BackgroundPage

Event Type

EventHandler<IPage>

Remarks

Only works with Chromium browser's persistent context.

Close

Emitted when Browser context gets closed. This might happen because of one of the following:

event EventHandler<IBrowserContext> Close

Event Type

EventHandler<IBrowserContext>

Console

Emitted when JavaScript within the page calls one of console API methods, e.g. console.log or console.dir.

The arguments passed into console.log and the page are available on the IConsoleMessage event handler argument.

**Usage**

context.Console += async (_, msg) =>
{
    foreach (var arg in msg.Args)
        Console.WriteLine(await arg.JsonValueAsync<object>());
};

await page.EvaluateAsync("console.log('hello', 5, { foo: 'bar' })");

event EventHandler<IConsoleMessage> Console

Event Type

EventHandler<IConsoleMessage>

Dialog

Emitted when a JavaScript dialog appears, such as alert, prompt, confirm or beforeunload. Listener **must** either AcceptAsync(string?) or DismissAsync() the dialog - otherwise the page will freeze waiting for the dialog, and actions like click will never finish.

**Usage**

Context.Dialog += async (_, dialog) =>
{
    await dialog.AcceptAsync();
};
event EventHandler<IDialog> Dialog

Event Type

EventHandler<IDialog>

Remarks

When no Dialog or Dialog listeners are present, all dialogs are automatically dismissed.

Page

The event is emitted when a new Page is created in the BrowserContext. The page may still be loading. The event will also fire for popup pages. See also Popup to receive events about popups relevant to a specific page.

The earliest moment that page is available is when it has navigated to the initial url. For example, when opening a popup with window.open('http://example.com'), this event will fire when the network request to "http://example.com" is done and its response has started loading in the popup. If you would like to route/listen to this network request, use RouteAsync(string, Action<IRoute>, BrowserContextRouteOptions?) and Request respectively instead of similar methods on the IPage.

var popup = await context.RunAndWaitForPageAsync(async =>
{
    await page.GetByText("open new page").ClickAsync();
});
Console.WriteLine(await popup.EvaluateAsync<string>("location.href"));
event EventHandler<IPage> Page

Event Type

EventHandler<IPage>

Remarks

Use WaitForLoadStateAsync(LoadState?, PageWaitForLoadStateOptions?) to wait until the page gets to a particular state (you should not need it in most cases).

Request

Emitted when a request is issued from any pages created through this context. The object is read-only. To only listen for requests from a particular page, use Request.

In order to intercept and mutate requests, see RouteAsync(string, Action<IRoute>, BrowserContextRouteOptions?) or RouteAsync(string, Action<IRoute>, PageRouteOptions?).

event EventHandler<IRequest> Request

Event Type

EventHandler<IRequest>

RequestFailed

Emitted when a request fails, for example by timing out. To only listen for failed requests from a particular page, use RequestFailed.

event EventHandler<IRequest> RequestFailed

Event Type

EventHandler<IRequest>

Remarks

HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request will complete with RequestFinished event and not with RequestFailed.

RequestFinished

Emitted when a request finishes successfully after downloading the response body. For a successful response, the sequence of events is request, response and requestfinished. To listen for successful requests from a particular page, use RequestFinished.

event EventHandler<IRequest> RequestFinished

Event Type

EventHandler<IRequest>

Response

Emitted when status and headers are received for a request. For a successful response, the sequence of events is request, response and requestfinished. To listen for response events from a particular page, use Response.

event EventHandler<IResponse> Response

Event Type

EventHandler<IResponse>

WebError

Emitted when exception is unhandled in any of the pages in this context. To listen for errors from a particular page, use PageError instead.

event EventHandler<IWebError> WebError

Event Type

EventHandler<IWebError>