Skip to main content

Page

Page provides methods to interact with a single tab in a Browser, or an extension background page in Chromium. One Browser instance might have multiple Page instances.

This example creates a page, navigates it to a URL, and then saves a screenshot:

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

class PageExamples
{
public static async Task Run()
{
using var playwright = await Playwright.CreateAsync();
await using var browser = await playwright.Webkit.LaunchAsync();
var page = await browser.NewPageAsync();
await page.GotoAsync("https://www.theverge.com");
await page.ScreenshotAsync(new() { Path = "theverge.png" });
}
}

The Page class emits various events (described below) which can be handled using any of Node's native EventEmitter methods, such as on, once or removeListener.

This example logs a message for a single page load event:

page.Load += (_, _) => Console.WriteLine("Page loaded!");

To unsubscribe from events use the removeListener method:

void PageLoadHandler(object _, IPage p) {
Console.WriteLine("Page loaded!");
};

page.Load += PageLoadHandler;
// Do some work...
page.Load -= PageLoadHandler;

Methods

AddInitScriptAsync

Added before v1.9 page.AddInitScriptAsync

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

  • Whenever the page is navigated.
  • Whenever the child frame is attached or navigated. 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:

// preload.js
Math.random = () => 42;
await Page.AddInitScriptAsync(scriptPath: "./preload.js");
note

The order of evaluation of multiple scripts installed via BrowserContext.AddInitScriptAsync() and Page.AddInitScriptAsync() is not defined.

Arguments

  • script string | string#

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

Returns


AddLocatorHandlerAsync

Added in: v1.42 page.AddLocatorHandlerAsync

When testing a web page, sometimes unexpected overlays like a "Sign up" dialog appear and block actions you want to automate, e.g. clicking a button. These overlays don't always show up in the same way or at the same time, making them tricky to handle in automated tests.

This method lets you set up a special function, called a handler, that activates when it detects that overlay is visible. The handler's job is to remove the overlay, allowing your test to continue as if the overlay wasn't there.

Things to keep in mind:

  • When an overlay is shown predictably, we recommend explicitly waiting for it in your test and dismissing it as a part of your normal test flow, instead of using Page.AddLocatorHandlerAsync().
  • Playwright checks for the overlay every time before executing or retrying an action that requires an actionability check, or before performing an auto-waiting assertion check. When overlay is visible, Playwright calls the handler first, and then proceeds with the action/assertion. Note that the handler is only called when you perform an action/assertion - if the overlay becomes visible but you don't perform any actions, the handler will not be triggered.
  • After executing the handler, Playwright will ensure that overlay that triggered the handler is not visible anymore. You can opt-out of this behavior with noWaitAfter.
  • The execution time of the handler counts towards the timeout of the action/assertion that executed the handler. If your handler takes too long, it might cause timeouts.
  • You can register multiple handlers. However, only a single handler will be running at a time. Make sure the actions within a handler don't depend on another handler.
warning

Running the handler will alter your page state mid-test. For example it will change the currently focused element and move the mouse. Make sure that actions that run after the handler are self-contained and do not rely on the focus and mouse state being unchanged.

For example, consider a test that calls Locator.FocusAsync() followed by Keyboard.PressAsync(). If your handler clicks a button between these two actions, the focused element most likely will be wrong, and key press will happen on the unexpected element. Use Locator.PressAsync() instead to avoid this problem.

Another example is a series of mouse actions, where Mouse.MoveAsync() is followed by Mouse.DownAsync(). Again, when the handler runs between these two actions, the mouse position will be wrong during the mouse down. Prefer self-contained actions like Locator.ClickAsync() that do not rely on the state being unchanged by a handler.

Usage

An example that closes a "Sign up to the newsletter" dialog when it appears:

// Setup the handler.
await page.AddLocatorHandlerAsync(page.GetByText("Sign up to the newsletter"), async () => {
await page.GetByRole(AriaRole.Button, new() { Name = "No thanks" }).ClickAsync();
});

// Write the test as usual.
await page.GotoAsync("https://example.com");
await page.GetByRole("button", new() { Name = "Start here" }).ClickAsync();

An example that skips the "Confirm your security details" page when it is shown:

// Setup the handler.
await page.AddLocatorHandlerAsync(page.GetByText("Confirm your security details"), async () => {
await page.GetByRole(AriaRole.Button, new() { Name = "Remind me later" }).ClickAsync();
});

// Write the test as usual.
await page.GotoAsync("https://example.com");
await page.GetByRole("button", new() { Name = "Start here" }).ClickAsync();

An example with a custom callback on every actionability check. It uses a <body> locator that is always visible, so the handler is called before every actionability check. It is important to specify noWaitAfter, because the handler does not hide the <body> element.

// Setup the handler.
await page.AddLocatorHandlerAsync(page.Locator("body"), async () => {
await page.EvaluateAsync("window.removeObstructionsForTestIfNeeded()");
}, new() { NoWaitAfter = true });

// Write the test as usual.
await page.GotoAsync("https://example.com");
await page.GetByRole("button", new() { Name = "Start here" }).ClickAsync();

Handler takes the original locator as an argument. You can also automatically remove the handler after a number of invocations by setting times:

await page.AddLocatorHandlerAsync(page.GetByText("Sign up to the newsletter"), async locator => {
await locator.ClickAsync();
}, new() { Times = 1 });

Arguments

  • locator Locator#

    Locator that triggers the handler.

  • handler Func<Locator, Task>#

    Function that should be run once locator appears. This function should get rid of the element that blocks actions like click.

  • options PageAddLocatorHandlerOptions? (optional)

    • NoWaitAfter bool? (optional) Added in: v1.44#

      By default, after calling the handler Playwright will wait until the overlay becomes hidden, and only then Playwright will continue with the action/assertion that triggered the handler. This option allows to opt-out of this behavior, so that overlay can stay visible after the handler has run.

    • Times int? (optional) Added in: v1.44#

      Specifies the maximum number of times this handler should be called. Unlimited by default.

Returns


AddScriptTagAsync

Added before v1.9 page.AddScriptTagAsync

Adds a <script> tag into the page with the desired url or content. Returns the added tag when the script's onload fires or when the script content was injected into frame.

Usage

await Page.AddScriptTagAsync(options);

Arguments

  • options PageAddScriptTagOptions? (optional)
    • Content string? (optional)#

      Raw JavaScript content to be injected into frame.

    • Path string? (optional)#

      Path to the JavaScript file to be injected into frame. If path is a relative path, then it is resolved relative to the current working directory.

    • Type string? (optional)#

      Script type. Use 'module' in order to load a JavaScript ES6 module. See script for more details.

    • Url string? (optional)#

      URL of a script to be added.

Returns


AddStyleTagAsync

Added before v1.9 page.AddStyleTagAsync

Adds a <link rel="stylesheet"> tag into the page with the desired url or a <style type="text/css"> tag with the content. Returns the added tag when the stylesheet's onload fires or when the CSS content was injected into frame.

Usage

await Page.AddStyleTagAsync(options);

Arguments

  • options PageAddStyleTagOptions? (optional)
    • Content string? (optional)#

      Raw CSS content to be injected into frame.

    • Path string? (optional)#

      Path to the CSS file to be injected into frame. If path is a relative path, then it is resolved relative to the current working directory.

    • Url string? (optional)#

      URL of the <link> tag.

Returns


BringToFrontAsync

Added before v1.9 page.BringToFrontAsync

Brings page to front (activates tab).

Usage

await Page.BringToFrontAsync();

Returns


CloseAsync

Added before v1.9 page.CloseAsync

If runBeforeUnload is false, does not run any unload handlers and waits for the page to be closed. If runBeforeUnload is true the method will run unload handlers, but will not wait for the page to close.

By default, page.close() does not run beforeunload handlers.

note

if runBeforeUnload is passed as true, a beforeunload dialog might be summoned and should be handled manually via Page.Dialog event.

Usage

await Page.CloseAsync(options);

Arguments

  • options PageCloseOptions? (optional)
    • Reason string? (optional) Added in: v1.40#

      The reason to be reported to the operations interrupted by the page closure.

    • RunBeforeUnload bool? (optional)#

      Defaults to false. Whether to run the before unload page handlers.

Returns


ContentAsync

Added before v1.9 page.ContentAsync

Gets the full HTML contents of the page, including the doctype.

Usage

await Page.ContentAsync();

Returns


Context

Added before v1.9 page.Context

Get the browser context that the page belongs to.

Usage

Page.Context

Returns


DragAndDropAsync

Added in: v1.13 page.DragAndDropAsync

This method drags the source element to the target element. It will first move to the source element, perform a mousedown, then move to the target element and perform a mouseup.

Usage

await Page.DragAndDropAsync("#source", "#target");
// or specify exact positions relative to the top-left corners of the elements:
await Page.DragAndDropAsync("#source", "#target", new()
{
SourcePosition = new() { X = 34, Y = 7 },
TargetPosition = new() { X = 10, Y = 20 },
});

Arguments

  • source string#

    A selector to search for an element to drag. If there are multiple elements satisfying the selector, the first will be used.

  • target string#

    A selector to search for an element to drop onto. If there are multiple elements satisfying the selector, the first will be used.

  • options PageDragAndDropOptions? (optional)

    • Force bool? (optional)#

      Whether to bypass the actionability checks. Defaults to false.

    • NoWaitAfter bool? (optional)#

      Deprecated

      This option has no effect.

      This option has no effect.

    • SourcePosition SourcePosition? (optional) Added in: v1.14#

      • X [float]

      • Y [float]

      Clicks on the source element at this point relative to the top-left corner of the element's padding box. If not specified, some visible point of the element is used.

    • Strict bool? (optional) Added in: v1.14#

      When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

    • TargetPosition TargetPosition? (optional) Added in: v1.14#

      • X [float]

      • Y [float]

      Drops on the target element at this point relative to the top-left corner of the element's padding box. If not specified, some visible point of the element is used.

    • Timeout [float]? (optional)#

      Maximum time in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout() or Page.SetDefaultTimeout() methods.

    • Trial bool? (optional)#

      When set, this method only performs the actionability checks and skips the action. Defaults to false. Useful to wait until the element is ready for the action without performing it.

Returns


EmulateMediaAsync

Added before v1.9 page.EmulateMediaAsync

This method changes the CSS media type through the media argument, and/or the 'prefers-colors-scheme' media feature, using the colorScheme argument.

Usage

await page.EvaluateAsync("() => matchMedia('screen').matches");
// → true
await page.EvaluateAsync("() => matchMedia('print').matches");
// → false

await page.EmulateMediaAsync(new() { Media = Media.Print });
await page.EvaluateAsync("() => matchMedia('screen').matches");
// → false
await page.EvaluateAsync("() => matchMedia('print').matches");
// → true

await page.EmulateMediaAsync(new() { Media = Media.Screen });
await page.EvaluateAsync("() => matchMedia('screen').matches");
// → true
await page.EvaluateAsync("() => matchMedia('print').matches");
// → false
await page.EmulateMediaAsync(new() { ColorScheme = ColorScheme.Dark });
await page.EvaluateAsync("matchMedia('(prefers-color-scheme: dark)').matches");
// → true
await page.EvaluateAsync("matchMedia('(prefers-color-scheme: light)').matches");
// → false
await page.EvaluateAsync("matchMedia('(prefers-color-scheme: no-preference)').matches");
// → false

Arguments

  • options PageEmulateMediaOptions? (optional)
    • ColorScheme enum ColorScheme { Light, Dark, NoPreference, Null }? (optional) Added in: v1.9#

      Emulates 'prefers-colors-scheme' media feature, supported values are 'light', 'dark', 'no-preference'. Passing 'Null' disables color scheme emulation.

    • ForcedColors enum ForcedColors { Active, None, Null }? (optional) Added in: v1.15#

    • Media enum Media { Screen, Print, Null }? (optional) Added in: v1.9#

      Changes the CSS media type of the page. The only allowed values are 'Screen', 'Print' and 'Null'. Passing 'Null' disables CSS media emulation.

    • ReducedMotion enum ReducedMotion { Reduce, NoPreference, Null }? (optional) Added in: v1.12#

      Emulates 'prefers-reduced-motion' media feature, supported values are 'reduce', 'no-preference'. Passing null disables reduced motion emulation.

Returns


EvaluateAsync

Added before v1.9 page.EvaluateAsync

Returns the value of the expression invocation.

If the function passed to the Page.EvaluateAsync() returns a Promise, then Page.EvaluateAsync() would wait for the promise to resolve and return its value.

If the function passed to the Page.EvaluateAsync() returns a non-Serializable value, then Page.EvaluateAsync() resolves to undefined. Playwright also supports transferring some additional values that are not serializable by JSON: -0, NaN, Infinity, -Infinity.

Usage

Passing argument to expression:

var result = await page.EvaluateAsync<int>("([x, y]) => Promise.resolve(x * y)", new[] { 7, 8 });
Console.WriteLine(result);

A string can also be passed in instead of a function:

Console.WriteLine(await page.EvaluateAsync<int>("1 + 2")); // prints "3"

ElementHandle instances can be passed as an argument to the Page.EvaluateAsync():

var bodyHandle = await page.EvaluateAsync("document.body");
var html = await page.EvaluateAsync<string>("([body, suffix]) => body.innerHTML + suffix", new object [] { bodyHandle, "hello" });
await bodyHandle.DisposeAsync();

Arguments

  • expression string#

    JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the function is automatically invoked.

  • arg EvaluationArgument? (optional)#

    Optional argument to pass to expression.

Returns

  • [object]#

EvaluateHandleAsync

Added before v1.9 page.EvaluateHandleAsync

Returns the value of the expression invocation as a JSHandle.

The only difference between Page.EvaluateAsync() and Page.EvaluateHandleAsync() is that Page.EvaluateHandleAsync() returns JSHandle.

If the function passed to the Page.EvaluateHandleAsync() returns a Promise, then Page.EvaluateHandleAsync() would wait for the promise to resolve and return its value.

Usage

// Handle for the window object.
var aWindowHandle = await page.EvaluateHandleAsync("() => Promise.resolve(window)");

A string can also be passed in instead of a function:

var docHandle = await page.EvaluateHandleAsync("document"); // Handle for the `document`

JSHandle instances can be passed as an argument to the Page.EvaluateHandleAsync():

var handle = await page.EvaluateHandleAsync("() => document.body");
var resultHandle = await page.EvaluateHandleAsync("([body, suffix]) => body.innerHTML + suffix", new object[] { handle, "hello" });
Console.WriteLine(await resultHandle.JsonValueAsync<string>());
await resultHandle.DisposeAsync();

Arguments

  • expression string#

    JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the function is automatically invoked.

  • arg EvaluationArgument? (optional)#

    Optional argument to pass to expression.

Returns


ExposeBindingAsync

Added before v1.9 page.ExposeBindingAsync

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

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

See BrowserContext.ExposeBindingAsync() for the context-wide version.

note

Functions installed via Page.ExposeBindingAsync() survive navigations.

Usage

An example of exposing page URL to all frames in a page:

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

class PageExamples
{
public static async Task Main()
{
using var playwright = await Playwright.CreateAsync();
await using var browser = await playwright.Webkit.LaunchAsync(new()
{
Headless = false,
});
var page = await browser.NewPageAsync();

await page.ExposeBindingAsync("pageUrl", (source) => source.Page.Url);
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.ClickAsync("button");
}
}

Arguments

  • name string#

    Name of the function on the window object.

  • callback Action<BindingSource, T, [TResult]>#

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

  • options PageExposeBindingOptions? (optional)

    • Handle bool? (optional)#

      Deprecated

      This option will be removed in the future.

      Whether to pass the argument as a handle, instead of passing by value. When passing a handle, only one argument is supported. When passing by value, multiple arguments are supported.

Returns


ExposeFunctionAsync

Added before v1.9 page.ExposeFunctionAsync

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

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

See BrowserContext.ExposeFunctionAsync() for context-wide exposed function.

note

Functions installed via Page.ExposeFunctionAsync() survive navigations.

Usage

An example of adding a sha256 function to the page:

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

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

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

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.ClickAsync("button");
Console.WriteLine(await page.TextContentAsync("div"));
}
}

Arguments

  • name string#

    Name of the function on the window object

  • callback Action<T, [TResult]>#

    Callback function which will be called in Playwright's context.

Returns


Frame

Added before v1.9 page.Frame

Returns frame matching the specified criteria. Either name or url must be specified.

Usage

var frame = page.Frame("frame-name");
var frame = page.FrameByUrl(".*domain.*");

Arguments

  • name string Added in: v1.9#

    Frame name specified in the iframe's name attribute.

Returns


FrameByUrl

Added in: v1.9 page.FrameByUrl

Returns frame with matching URL.

Usage

Page.FrameByUrl(url);

Arguments

Returns


FrameLocator

Added in: v1.17 page.FrameLocator

When working with iframes, you can create a frame locator that will enter the iframe and allow selecting elements in that iframe.

Usage

Following snippet locates element with text "Submit" in the iframe with id my-frame, like <iframe id="my-frame">:

var locator = page.FrameLocator("#my-iframe").GetByText("Submit");
await locator.ClickAsync();

Arguments

  • selector string#

    A selector to use when resolving DOM element.

Returns


Frames

Added before v1.9 page.Frames

An array of all frames attached to the page.

Usage

Page.Frames

Returns


GetByAltText

Added in: v1.27 page.GetByAltText

Allows locating elements by their alt text.

Usage

For example, this method will find the image by alt text "Playwright logo":

<img alt='Playwright logo'>
await page.GetByAltText("Playwright logo").ClickAsync();

Arguments

  • text string | Regex#

    Text to locate the element for.

  • options PageGetByAltTextOptions? (optional)

    • Exact bool? (optional)#

      Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a regular expression. Note that exact match still trims whitespace.

Returns


GetByLabel

Added in: v1.27 page.GetByLabel

Allows locating input elements by the text of the associated <label> or aria-labelledby element, or by the aria-label attribute.

Usage

For example, this method will find inputs by label "Username" and "Password" in the following DOM:

<input aria-label="Username">
<label for="password-input">Password:</label>
<input id="password-input">
await page.GetByLabel("Username").FillAsync("john");
await page.GetByLabel("Password").FillAsync("secret");

Arguments

  • text string | Regex#

    Text to locate the element for.

  • options PageGetByLabelOptions? (optional)

    • Exact bool? (optional)#

      Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a regular expression. Note that exact match still trims whitespace.

Returns


GetByPlaceholder

Added in: v1.27 page.GetByPlaceholder

Allows locating input elements by the placeholder text.

Usage

For example, consider the following DOM structure.

<input type="email" placeholder="name@example.com" />

You can fill the input after locating it by the placeholder text:

await page
.GetByPlaceholder("name@example.com")
.FillAsync("playwright@microsoft.com");

Arguments

  • text string | Regex#

    Text to locate the element for.

  • options PageGetByPlaceholderOptions? (optional)

    • Exact bool? (optional)#

      Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a regular expression. Note that exact match still trims whitespace.

Returns


GetByRole

Added in: v1.27 page.GetByRole

Allows locating elements by their ARIA role, ARIA attributes and accessible name.

Usage

Consider the following DOM structure.

<h3>Sign up</h3>
<label>
<input type="checkbox" /> Subscribe
</label>
<br/>
<button>Submit</button>

You can locate each element by it's implicit role:

await Expect(Page
.GetByRole(AriaRole.Heading, new() { Name = "Sign up" }))
.ToBeVisibleAsync();

await page
.GetByRole(AriaRole.Checkbox, new() { Name = "Subscribe" })
.CheckAsync();

await page
.GetByRole(AriaRole.Button, new() {
NameRegex = new Regex("submit", RegexOptions.IgnoreCase)
})
.ClickAsync();

Arguments

  • role enum AriaRole { Alert, Alertdialog, Application, Article, Banner, Blockquote, Button, Caption, Cell, Checkbox, Code, Columnheader, Combobox, Complementary, Contentinfo, Definition, Deletion, Dialog, Directory, Document, Emphasis, Feed, Figure, Form, Generic, Grid, Gridcell, Group, Heading, Img, Insertion, Link, List, Listbox, Listitem, Log, Main, Marquee, Math, Meter, Menu, Menubar, Menuitem, Menuitemcheckbox, Menuitemradio, Navigation, None, Note, Option, Paragraph, Presentation, Progressbar, Radio, Radiogroup, Region, Row, Rowgroup, Rowheader, Scrollbar, Search, Searchbox, Separator, Slider, Spinbutton, Status, Strong, Subscript, Superscript, Switch, Tab, Table, Tablist, Tabpanel, Term, Textbox, Time, Timer, Toolbar, Tooltip, Tree, Treegrid, Treeitem }#

    Required aria role.

  • options PageGetByRoleOptions? (optional)

    • Checked bool? (optional)#

      An attribute that is usually set by aria-checked or native <input type=checkbox> controls.

      Learn more about aria-checked.

    • Disabled bool? (optional)#

      An attribute that is usually set by aria-disabled or disabled.

      note

      Unlike most other attributes, disabled is inherited through the DOM hierarchy. Learn more about aria-disabled.

    • Exact bool? (optional) Added in: v1.28#

      Whether name is matched exactly: case-sensitive and whole-string. Defaults to false. Ignored when name is a regular expression. Note that exact match still trims whitespace.

    • Expanded bool? (optional)#

      An attribute that is usually set by aria-expanded.

      Learn more about aria-expanded.

    • IncludeHidden bool? (optional)#

      Option that controls whether hidden elements are matched. By default, only non-hidden elements, as defined by ARIA, are matched by role selector.

      Learn more about aria-hidden.

    • Level int? (optional)#

      A number attribute that is usually present for roles heading, listitem, row, treeitem, with default values for <h1>-<h6> elements.

      Learn more about aria-level.

    • Name|NameRegex string? | Regex? (optional)#

      Option to match the accessible name. By default, matching is case-insensitive and searches for a substring, use exact to control this behavior.

      Learn more about accessible name.

    • Pressed bool? (optional)#

      An attribute that is usually set by aria-pressed.

      Learn more about aria-pressed.

    • Selected bool? (optional)#

      An attribute that is usually set by aria-selected.

      Learn more about aria-selected.

Returns

Details

Role selector does not replace accessibility audits and conformance tests, but rather gives early feedback about the ARIA guidelines.

Many html elements have an implicitly defined role that is recognized by the role selector. You can find all the supported roles here. ARIA guidelines do not recommend duplicating implicit roles and attributes by setting role and/or aria-* attributes to default values.


GetByTestId

Added in: v1.27 page.GetByTestId

Locate element by the test id.

Usage

Consider the following DOM structure.

<button data-testid="directions">Itinéraire</button>

You can locate the element by it's test id:

await page.GetByTestId("directions").ClickAsync();

Arguments

Returns

Details

By default, the data-testid attribute is used as a test id. Use Selectors.SetTestIdAttribute() to configure a different test id attribute if necessary.


GetByText

Added in: v1.27 page.GetByText

Allows locating elements that contain given text.

See also Locator.Filter() that allows to match by another criteria, like an accessible role, and then filter by the text content.

Usage

Consider the following DOM structure:

<div>Hello <span>world</span></div>
<div>Hello</div>

You can locate by text substring, exact string, or a regular expression:

// Matches <span>
page.GetByText("world");

// Matches first <div>
page.GetByText("Hello world");

// Matches second <div>
page.GetByText("Hello", new() { Exact = true });

// Matches both <div>s
page.GetByText(new Regex("Hello"));

// Matches second <div>
page.GetByText(new Regex("^hello$", RegexOptions.IgnoreCase));

Arguments

  • text string | Regex#

    Text to locate the element for.

  • options PageGetByTextOptions? (optional)

    • Exact bool? (optional)#

      Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a regular expression. Note that exact match still trims whitespace.

Returns

Details

Matching by text always normalizes whitespace, even with exact match. For example, it turns multiple spaces into one, turns line breaks into spaces and ignores leading and trailing whitespace.

Input elements of the type button and submit are matched by their value instead of the text content. For example, locating by text "Log in" matches <input type=button value="Log in">.


GetByTitle

Added in: v1.27 page.GetByTitle

Allows locating elements by their title attribute.

Usage

Consider the following DOM structure.

<span title='Issues count'>25 issues</span>

You can check the issues count after locating it by the title text:

await Expect(Page.GetByTitle("Issues count")).toHaveText("25 issues");

Arguments

  • text string | Regex#

    Text to locate the element for.

  • options PageGetByTitleOptions? (optional)

    • Exact bool? (optional)#

      Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a regular expression. Note that exact match still trims whitespace.

Returns


GoBackAsync

Added before v1.9 page.GoBackAsync

Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. If cannot go back, returns null.

Navigate to the previous page in history.

Usage

await Page.GoBackAsync(options);

Arguments

  • options PageGoBackOptions? (optional)
    • Timeout [float]? (optional)#

      Maximum operation time in milliseconds, defaults to 30 seconds, pass 0 to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultNavigationTimeout(), BrowserContext.SetDefaultTimeout(), Page.SetDefaultNavigationTimeout() or Page.SetDefaultTimeout() methods.

    • WaitUntil enum WaitUntilState { Load, DOMContentLoaded, NetworkIdle, Commit }? (optional)#

      When to consider operation succeeded, defaults to load. Events can be either:

      • 'domcontentloaded' - consider operation to be finished when the DOMContentLoaded event is fired.
      • 'load' - consider operation to be finished when the load event is fired.
      • 'networkidle' - DISCOURAGED consider operation to be finished when there are no network connections for at least 500 ms. Don't use this method for testing, rely on web assertions to assess readiness instead.
      • 'commit' - consider operation to be finished when network response is received and the document started loading.

Returns


GoForwardAsync

Added before v1.9 page.GoForwardAsync

Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. If cannot go forward, returns null.

Navigate to the next page in history.

Usage

await Page.GoForwardAsync(options);

Arguments

  • options PageGoForwardOptions? (optional)
    • Timeout [float]? (optional)#

      Maximum operation time in milliseconds, defaults to 30 seconds, pass 0 to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultNavigationTimeout(), BrowserContext.SetDefaultTimeout(), Page.SetDefaultNavigationTimeout() or Page.SetDefaultTimeout() methods.

    • WaitUntil enum WaitUntilState { Load, DOMContentLoaded, NetworkIdle, Commit }? (optional)#

      When to consider operation succeeded, defaults to load. Events can be either:

      • 'domcontentloaded' - consider operation to be finished when the DOMContentLoaded event is fired.
      • 'load' - consider operation to be finished when the load event is fired.
      • 'networkidle' - DISCOURAGED consider operation to be finished when there are no network connections for at least 500 ms. Don't use this method for testing, rely on web assertions to assess readiness instead.
      • 'commit' - consider operation to be finished when network response is received and the document started loading.

Returns


GotoAsync

Added before v1.9 page.GotoAsync

Returns the main resource response. In case of multiple redirects, the navigation will resolve with the first non-redirect response.

The method will throw an error if:

  • there's an SSL error (e.g. in case of self-signed certificates).
  • target URL is invalid.
  • the timeout is exceeded during navigation.
  • the remote server does not respond or is unreachable.
  • the main resource failed to load.

The method will not throw an error when any valid HTTP status code is returned by the remote server, including 404 "Not Found" and 500 "Internal Server Error". The status code for such responses can be retrieved by calling Response.Status.

note

The method either throws an error or returns a main resource response. The only exceptions are navigation to about:blank or navigation to the same URL with a different hash, which would succeed and return null.

note

Headless mode doesn't support navigation to a PDF document. See the upstream issue.

Usage

await Page.GotoAsync(url, options);

Arguments

  • url string#

    URL to navigate page to. The url should include scheme, e.g. https://. When a baseURL via the context options was provided and the passed URL is a path, it gets merged via the new URL() constructor.

  • options PageGotoOptions? (optional)

    • Referer string? (optional)#

      Referer header value. If provided it will take preference over the referer header value set by Page.SetExtraHTTPHeadersAsync().

    • Timeout [float]? (optional)#

      Maximum operation time in milliseconds, defaults to 30 seconds, pass 0 to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultNavigationTimeout(), BrowserContext.SetDefaultTimeout(), Page.SetDefaultNavigationTimeout() or Page.SetDefaultTimeout() methods.

    • WaitUntil enum WaitUntilState { Load, DOMContentLoaded, NetworkIdle, Commit }? (optional)#

      When to consider operation succeeded, defaults to load. Events can be either:

      • 'domcontentloaded' - consider operation to be finished when the DOMContentLoaded event is fired.
      • 'load' - consider operation to be finished when the load event is fired.
      • 'networkidle' - DISCOURAGED consider operation to be finished when there are no network connections for at least 500 ms. Don't use this method for testing, rely on web assertions to assess readiness instead.
      • 'commit' - consider operation to be finished when network response is received and the document started loading.

Returns


IsClosed

Added before v1.9 page.IsClosed

Indicates that the page has been closed.

Usage

Page.IsClosed

Returns


Locator

Added in: v1.14 page.Locator

The method returns an element locator that can be used to perform actions on this page / frame. Locator is resolved to the element immediately before performing an action, so a series of actions on the same locator can in fact be performed on different DOM elements. That would happen if the DOM structure between those actions has changed.

Learn more about locators.

Usage

Page.Locator(selector, options);

Arguments

  • selector string#

    A selector to use when resolving DOM element.

  • options PageLocatorOptions? (optional)

    • Has Locator? (optional)#

      Narrows down the results of the method to those which contain elements matching this relative locator. For example, article that has text=Playwright matches <article><div>Playwright</div></article>.

      Inner locator must be relative to the outer locator and is queried starting with the outer locator match, not the document root. For example, you can find content that has div in <article><content><div>Playwright</div></content></article>. However, looking for content that has article div will fail, because the inner locator must be relative and should not use any elements outside the content.

      Note that outer and inner locators must belong to the same frame. Inner locator must not contain FrameLocators.

    • HasNot Locator? (optional) Added in: v1.33#

      Matches elements that do not contain an element that matches an inner locator. Inner locator is queried against the outer one. For example, article that does not have div matches <article><span>Playwright</span></article>.

      Note that outer and inner locators must belong to the same frame. Inner locator must not contain FrameLocators.

    • HasNotText|HasNotTextRegex string? | Regex? (optional) Added in: v1.33#

      Matches elements that do not contain specified text somewhere inside, possibly in a child or a descendant element. When passed a string, matching is case-insensitive and searches for a substring.

    • HasText|HasTextRegex string? | Regex? (optional)#

      Matches elements containing specified text somewhere inside, possibly in a child or a descendant element. When passed a string, matching is case-insensitive and searches for a substring. For example, "Playwright" matches <article><div>Playwright</div></article>.

Returns


MainFrame

Added before v1.9 page.MainFrame

The page's main frame. Page is guaranteed to have a main frame which persists during navigations.

Usage

Page.MainFrame

Returns


OpenerAsync

Added before v1.9 page.OpenerAsync

Returns the opener for popup pages and null for others. If the opener has been closed already the returns null.

Usage

await Page.OpenerAsync();

Returns


PauseAsync

Added in: v1.9 page.PauseAsync

Pauses script execution. Playwright will stop executing the script and wait for the user to either press 'Resume' button in the page overlay or to call playwright.resume() in the DevTools console.

User can inspect selectors or perform manual steps while paused. Resume will continue running the original script from the place it was paused.

note

This method requires Playwright to be started in a headed mode, with a falsy headless value in the BrowserType.LaunchAsync().

Usage

await Page.PauseAsync();

Returns


PdfAsync

Added before v1.9 page.PdfAsync

Returns the PDF buffer.

note

Generating a pdf is currently only supported in Chromium headless.

page.pdf() generates a pdf of the page with print css media. To generate a pdf with screen media, call Page.EmulateMediaAsync() before calling page.pdf():

note

By default, page.pdf() generates a pdf with modified colors for printing. Use the -webkit-print-color-adjust property to force rendering of exact colors.

Usage

// Generates a PDF with 'screen' media type
await page.EmulateMediaAsync(new() { Media = Media.Screen });
await page.PdfAsync(new() { Path = "page.pdf" });

The width, height, and margin options accept values labeled with units. Unlabeled values are treated as pixels.

A few examples:

  • page.pdf({width: 100}) - prints with width set to 100 pixels
  • page.pdf({width: '100px'}) - prints with width set to 100 pixels
  • page.pdf({width: '10cm'}) - prints with width set to 10 centimeters.

All possible units are:

  • px - pixel
  • in - inch
  • cm - centimeter
  • mm - millimeter

The format options are:

  • Letter: 8.5in x 11in
  • Legal: 8.5in x 14in
  • Tabloid: 11in x 17in
  • Ledger: 17in x 11in
  • A0: 33.1in x 46.8in
  • A1: 23.4in x 33.1in
  • A2: 16.54in x 23.4in
  • A3: 11.7in x 16.54in
  • A4: 8.27in x 11.7in
  • A5: 5.83in x 8.27in
  • A6: 4.13in x 5.83in
note

headerTemplate and footerTemplate markup have the following limitations: > 1. Script tags inside templates are not evaluated. > 2. Page styles are not visible inside templates.

Arguments

  • options PagePdfOptions? (optional)
    • DisplayHeaderFooter bool? (optional)#

      Display header and footer. Defaults to false.

    • FooterTemplate string? (optional)#

      HTML template for the print footer. Should use the same format as the headerTemplate.

    • Format string? (optional)#

      Paper format. If set, takes priority over width or height options. Defaults to 'Letter'.

    • HeaderTemplate string? (optional)#

      HTML template for the print header. Should be valid HTML markup with following classes used to inject printing values into them:

      • 'date' formatted print date
      • 'title' document title
      • 'url' document location
      • 'pageNumber' current page number
      • 'totalPages' total pages in the document
    • Height string? (optional)#

      Paper height, accepts values labeled with units.

    • Landscape bool? (optional)#

      Paper orientation. Defaults to false.

    • Margin Margin? (optional)#

      • Top string? (optional)

        Top margin, accepts values labeled with units. Defaults to 0.

      • Right string? (optional)

        Right margin, accepts values labeled with units. Defaults to 0.

      • Bottom string? (optional)

        Bottom margin, accepts values labeled with units. Defaults to 0.

      • Left string? (optional)

        Left margin, accepts values labeled with units. Defaults to 0.

      Paper margins, defaults to none.

    • Outline bool? (optional) Added in: v1.42#

      Whether or not to embed the document outline into the PDF. Defaults to false.

    • PageRanges string? (optional)#

      Paper ranges to print, e.g., '1-5, 8, 11-13'. Defaults to the empty string, which means print all pages.

    • Path string? (optional)#

      The file path to save the PDF to. If path is a relative path, then it is resolved relative to the current working directory. If no path is provided, the PDF won't be saved to the disk.

    • PreferCSSPageSize bool? (optional)#

      Give any CSS @page size declared in the page priority over what is declared in width and height or format options. Defaults to false, which will scale the content to fit the paper size.

    • PrintBackground bool? (optional)#

      Print background graphics. Defaults to false.

    • Scale [float]? (optional)#

      Scale of the webpage rendering. Defaults to 1. Scale amount must be between 0.1 and 2.

    • Tagged bool? (optional) Added in: v1.42#

      Whether or not to generate tagged (accessible) PDF. Defaults to false.

    • Width string? (optional)#

      Paper width, accepts values labeled with units.

Returns


ReloadAsync

Added before v1.9 page.ReloadAsync

This method reloads the current page, in the same way as if the user had triggered a browser refresh. Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect.

Usage

await Page.ReloadAsync(options);

Arguments

  • options PageReloadOptions? (optional)
    • Timeout [float]? (optional)#

      Maximum operation time in milliseconds, defaults to 30 seconds, pass 0 to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultNavigationTimeout(), BrowserContext.SetDefaultTimeout(), Page.SetDefaultNavigationTimeout() or Page.SetDefaultTimeout() methods.

    • WaitUntil enum WaitUntilState { Load, DOMContentLoaded, NetworkIdle, Commit }? (optional)#

      When to consider operation succeeded, defaults to load. Events can be either:

      • 'domcontentloaded' - consider operation to be finished when the DOMContentLoaded event is fired.
      • 'load' - consider operation to be finished when the load event is fired.
      • 'networkidle' - DISCOURAGED consider operation to be finished when there are no network connections for at least 500 ms. Don't use this method for testing, rely on web assertions to assess readiness instead.
      • 'commit' - consider operation to be finished when network response is received and the document started loading.

Returns


RemoveLocatorHandlerAsync

Added in: v1.44 page.RemoveLocatorHandlerAsync

Removes all locator handlers added by Page.AddLocatorHandlerAsync() for a specific locator.

Usage

await Page.RemoveLocatorHandlerAsync(locator);

Arguments

Returns


RouteAsync

Added before v1.9 page.RouteAsync

Routing provides the capability to modify network requests that are made by a page.

Once routing is enabled, every request matching the url pattern will stall unless it's continued, fulfilled or aborted.

note

The handler will only be called for the first url if the response is a redirect.

note

Page.RouteAsync() 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 to 'block'.

note

Page.RouteAsync() will not intercept the first request of a popup page. Use BrowserContext.RouteAsync() instead.

Usage

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

var page = await browser.NewPageAsync();
await page.RouteAsync("**/*.{png,jpg,jpeg}", async r => await r.AbortAsync());
await page.GotoAsync("https://www.microsoft.com");

or the same snippet using a regex pattern instead:

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

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 take precedence over browser context routes (set up with BrowserContext.RouteAsync()) when request matches both handlers.

To remove a route with its handler you can use Page.UnrouteAsync().

note

Enabling routing disables http cache.

Arguments

  • url string | Regex | Func<string, bool>#

    A glob pattern, regex pattern or predicate receiving URL 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<Route>#

    handler function to route the request.

  • options PageRouteOptions? (optional)

    • Times int? (optional) Added in: v1.15#

      How often a route should be used. By default it will be used every time.

Returns


RouteFromHARAsync

Added in: v1.23 page.RouteFromHARAsync

If specified the network requests that are made in the page 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 to 'block'.

Usage

await Page.RouteFromHARAsync(har, options);

Arguments

  • 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 PageRouteFromHAROptions? (optional)

    • NotFound enum HarNotFound { Abort, Fallback }? (optional)#

      • If set to 'abort' any request not found in the HAR file will be aborted.
      • If set to 'fallback' missing requests will be sent to the network.

      Defaults to abort.

    • Update bool? (optional)#

      If specified, updates the given HAR with the actual network information instead of serving from file. The file is written to disk when BrowserContext.CloseAsync() is called.

    • UpdateContent enum RouteFromHarUpdateContentPolicy { Embed, Attach }? (optional) Added in: v1.32#

      Optional setting to control resource content management. If attach is specified, resources are persisted as separate files or entries in the ZIP archive. If embed is specified, content is stored inline the HAR file.

    • UpdateMode enum HarMode { Full, Minimal }? (optional) Added in: v1.32#

      When set to minimal, only record information necessary for routing from HAR. This omits sizes, timing, page, cookies, security and other types of HAR information that are not used when replaying from HAR. Defaults to minimal.

    • Url|UrlRegex string? | Regex? (optional)#

      A glob pattern, regular expression or predicate to match the request URL. Only requests with URL matching the pattern will be served from the HAR file. If not specified, all requests are served from the HAR file.

Returns


RunAndWaitForConsoleMessageAsync

Added in: v1.9 page.RunAndWaitForConsoleMessageAsync

Performs action and waits for a ConsoleMessage to be logged by in the page. If predicate is provided, it passes ConsoleMessage 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 Page.Console event is fired.

Usage

await Page.RunAndWaitForConsoleMessageAsync(action, options);

Arguments

  • action Func<Task> Added in: v1.12#

    Action that triggers the event.

  • options PageRunAndWaitForConsoleMessageOptions? (optional)

    • Predicate Func<ConsoleMessage?, bool> (optional)#

      Receives the ConsoleMessage object and resolves to truthy value when the waiting should resolve.

    • Timeout [float]? (optional)#

      Maximum time to wait for in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout().

Returns


WaitForConsoleMessageAsync

Added in: v1.9 page.WaitForConsoleMessageAsync

Performs action and waits for a ConsoleMessage to be logged by in the page. If predicate is provided, it passes ConsoleMessage 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 Page.Console event is fired.

Usage

await Page.WaitForConsoleMessageAsync(action, options);

Arguments

  • options PageRunAndWaitForConsoleMessageOptions? (optional)
    • Predicate Func<ConsoleMessage?, bool> (optional)#

      Receives the ConsoleMessage object and resolves to truthy value when the waiting should resolve.

    • Timeout [float]? (optional)#

      Maximum time to wait for in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout().

Returns


RunAndWaitForDownloadAsync

Added in: v1.9 page.RunAndWaitForDownloadAsync

Performs action and waits for a new Download. If predicate is provided, it passes Download value into the predicate function and waits for predicate(download) to return a truthy value. Will throw an error if the page is closed before the download event is fired.

Usage

await Page.RunAndWaitForDownloadAsync(action, options);

Arguments

  • action Func<Task> Added in: v1.12#

    Action that triggers the event.

  • options PageRunAndWaitForDownloadOptions? (optional)

    • Predicate Func<Download?, bool> (optional)#

      Receives the Download object and resolves to truthy value when the waiting should resolve.

    • Timeout [float]? (optional)#

      Maximum time to wait for in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout().

Returns


WaitForDownloadAsync

Added in: v1.9 page.WaitForDownloadAsync

Performs action and waits for a new Download. If predicate is provided, it passes Download value into the predicate function and waits for predicate(download) to return a truthy value. Will throw an error if the page is closed before the download event is fired.

Usage

await Page.WaitForDownloadAsync(action, options);

Arguments

  • options PageRunAndWaitForDownloadOptions? (optional)
    • Predicate Func<Download?, bool> (optional)#

      Receives the Download object and resolves to truthy value when the waiting should resolve.

    • Timeout [float]? (optional)#

      Maximum time to wait for in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout().

Returns


RunAndWaitForFileChooserAsync

Added in: v1.9 page.RunAndWaitForFileChooserAsync

Performs action and waits for a new FileChooser to be created. If predicate is provided, it passes FileChooser value into the predicate function and waits for predicate(fileChooser) to return a truthy value. Will throw an error if the page is closed before the file chooser is opened.

Usage

await Page.RunAndWaitForFileChooserAsync(action, options);

Arguments

  • action Func<Task> Added in: v1.12#

    Action that triggers the event.

  • options PageRunAndWaitForFileChooserOptions? (optional)

    • Predicate Func<FileChooser?, bool> (optional)#

      Receives the FileChooser object and resolves to truthy value when the waiting should resolve.

    • Timeout [float]? (optional)#

      Maximum time to wait for in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout().

Returns


WaitForFileChooserAsync

Added in: v1.9 page.WaitForFileChooserAsync

Performs action and waits for a new FileChooser to be created. If predicate is provided, it passes FileChooser value into the predicate function and waits for predicate(fileChooser) to return a truthy value. Will throw an error if the page is closed before the file chooser is opened.

Usage

await Page.WaitForFileChooserAsync(action, options);

Arguments

  • options PageRunAndWaitForFileChooserOptions? (optional)
    • Predicate Func<FileChooser?, bool> (optional)#

      Receives the FileChooser object and resolves to truthy value when the waiting should resolve.

    • Timeout [float]? (optional)#

      Maximum time to wait for in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout().

Returns


RunAndWaitForPopupAsync

Added in: v1.9 page.RunAndWaitForPopupAsync

Performs action and waits for a popup Page. If predicate is provided, it passes [Popup] value into the predicate function and waits for predicate(page) to return a truthy value. Will throw an error if the page is closed before the popup event is fired.

Usage

await Page.RunAndWaitForPopupAsync(action, options);

Arguments

  • action Func<Task> Added in: v1.12#

    Action that triggers the event.

  • options PageRunAndWaitForPopupOptions? (optional)

    • Predicate Func<Page?, bool> (optional)#

      Receives the Page object and resolves to truthy value when the waiting should resolve.

    • Timeout [float]? (optional)#

      Maximum time to wait for in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout().

Returns


WaitForPopupAsync

Added in: v1.9 page.WaitForPopupAsync

Performs action and waits for a popup Page. If predicate is provided, it passes [Popup] value into the predicate function and waits for predicate(page) to return a truthy value. Will throw an error if the page is closed before the popup event is fired.

Usage

await Page.WaitForPopupAsync(action, options);

Arguments

  • options PageRunAndWaitForPopupOptions? (optional)
    • Predicate Func<Page?, bool> (optional)#

      Receives the Page object and resolves to truthy value when the waiting should resolve.

    • Timeout [float]? (optional)#

      Maximum time to wait for in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout().

Returns


RunAndWaitForRequestAsync

Added before v1.9 page.RunAndWaitForRequestAsync

Waits for the matching request and returns it. See waiting for event for more details about events.

Usage

// Waits for the next request with the specified url.
await page.RunAndWaitForRequestAsync(async () =>
{
await page.GetByText("trigger request").ClickAsync();
}, "http://example.com/resource");

// Alternative way with a predicate.
await page.RunAndWaitForRequestAsync(async () =>
{
await page.GetByText("trigger request").ClickAsync();
}, request => request.Url == "https://example.com" && request.Method == "GET");

Arguments

  • action Func<Task> Added in: v1.12#

    Action that triggers the event.

  • urlOrPredicate string | Regex | Func<Request, bool>#

    Request URL string, regex or predicate receiving Request object. When a baseURL via the context options was provided and the passed URL is a path, it gets merged via the new URL() constructor.

  • options PageRunAndWaitForRequestOptions? (optional)

    • Timeout [float]? (optional)#

      Maximum wait time in milliseconds, defaults to 30 seconds, pass 0 to disable the timeout. The default value can be changed by using the Page.SetDefaultTimeout() method.

Returns


WaitForRequestAsync

Added before v1.9 page.WaitForRequestAsync

Waits for the matching request and returns it. See waiting for event for more details about events.

Usage

// Waits for the next request with the specified url.
await page.RunAndWaitForRequestAsync(async () =>
{
await page.GetByText("trigger request").ClickAsync();
}, "http://example.com/resource");

// Alternative way with a predicate.
await page.RunAndWaitForRequestAsync(async () =>
{
await page.GetByText("trigger request").ClickAsync();
}, request => request.Url == "https://example.com" && request.Method == "GET");

Arguments

  • urlOrPredicate string | Regex | Func<Request, bool>#

    Request URL string, regex or predicate receiving Request object. When a baseURL via the context options was provided and the passed URL is a path, it gets merged via the new URL() constructor.

  • options PageRunAndWaitForRequestOptions? (optional)

    • Timeout [float]? (optional)#

      Maximum wait time in milliseconds, defaults to 30 seconds, pass 0 to disable the timeout. The default value can be changed by using the Page.SetDefaultTimeout() method.

Returns


RunAndWaitForRequestFinishedAsync

Added in: v1.12 page.RunAndWaitForRequestFinishedAsync

Performs action and waits for a Request to finish loading. If predicate is provided, it passes Request value into the predicate function and waits for predicate(request) to return a truthy value. Will throw an error if the page is closed before the Page.RequestFinished event is fired.

Usage

await Page.RunAndWaitForRequestFinishedAsync(action, options);

Arguments

  • action Func<Task>#

    Action that triggers the event.

  • options PageRunAndWaitForRequestFinishedOptions? (optional)

    • Predicate Func<Request?, bool> (optional)#

      Receives the Request object and resolves to truthy value when the waiting should resolve.

    • Timeout [float]? (optional)#

      Maximum time to wait for in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout().

Returns


WaitForRequestFinishedAsync

Added in: v1.12 page.WaitForRequestFinishedAsync

Performs action and waits for a Request to finish loading. If predicate is provided, it passes Request value into the predicate function and waits for predicate(request) to return a truthy value. Will throw an error if the page is closed before the Page.RequestFinished event is fired.

Usage

await Page.WaitForRequestFinishedAsync(action, options);

Arguments

  • options PageRunAndWaitForRequestFinishedOptions? (optional)
    • Predicate Func<Request?, bool> (optional)#

      Receives the Request object and resolves to truthy value when the waiting should resolve.

    • Timeout [float]? (optional)#

      Maximum time to wait for in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout().

Returns


RunAndWaitForResponseAsync

Added before v1.9 page.RunAndWaitForResponseAsync

Returns the matched response. See waiting for event for more details about events.

Usage

// Waits for the next response with the specified url.
await page.RunAndWaitForResponseAsync(async () =>
{
await page.GetByText("trigger response").ClickAsync();
}, "http://example.com/resource");

// Alternative way with a predicate.
await page.RunAndWaitForResponseAsync(async () =>
{
await page.GetByText("trigger response").ClickAsync();
}, response => response.Url == "https://example.com" && response.Status == 200 && response.Request.Method == "GET");

Arguments

  • action Func<Task> Added in: v1.12#

    Action that triggers the event.

  • urlOrPredicate string | Regex | Func<Response, bool>#

    Request URL string, regex or predicate receiving Response object. When a baseURL via the context options was provided and the passed URL is a path, it gets merged via the new URL() constructor.

  • options PageRunAndWaitForResponseOptions? (optional)

Returns


WaitForResponseAsync

Added before v1.9 page.WaitForResponseAsync

Returns the matched response. See waiting for event for more details about events.

Usage

// Waits for the next response with the specified url.
await page.RunAndWaitForResponseAsync(async () =>
{
await page.GetByText("trigger response").ClickAsync();
}, "http://example.com/resource");

// Alternative way with a predicate.
await page.RunAndWaitForResponseAsync(async () =>
{
await page.GetByText("trigger response").ClickAsync();
}, response => response.Url == "https://example.com" && response.Status == 200 && response.Request.Method == "GET");

Arguments

  • urlOrPredicate string | Regex | Func<Response, bool>#

    Request URL string, regex or predicate receiving Response object. When a baseURL via the context options was provided and the passed URL is a path, it gets merged via the new URL() constructor.

  • options PageRunAndWaitForResponseOptions? (optional)

Returns


RunAndWaitForWebSocketAsync

Added in: v1.9 page.RunAndWaitForWebSocketAsync

Performs action and waits for a new WebSocket. If predicate is provided, it passes WebSocket value into the predicate function and waits for predicate(webSocket) to return a truthy value. Will throw an error if the page is closed before the WebSocket event is fired.

Usage

await Page.RunAndWaitForWebSocketAsync(action, options);

Arguments

  • action Func<Task> Added in: v1.12#

    Action that triggers the event.

  • options PageRunAndWaitForWebSocketOptions? (optional)

    • Predicate Func<WebSocket?, bool> (optional)#

      Receives the WebSocket object and resolves to truthy value when the waiting should resolve.

    • Timeout [float]? (optional)#

      Maximum time to wait for in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout().

Returns


WaitForWebSocketAsync

Added in: v1.9 page.WaitForWebSocketAsync

Performs action and waits for a new WebSocket. If predicate is provided, it passes WebSocket value into the predicate function and waits for predicate(webSocket) to return a truthy value. Will throw an error if the page is closed before the WebSocket event is fired.

Usage

await Page.WaitForWebSocketAsync(action, options);

Arguments

  • options PageRunAndWaitForWebSocketOptions? (optional)
    • Predicate Func<WebSocket?, bool> (optional)#

      Receives the WebSocket object and resolves to truthy value when the waiting should resolve.

    • Timeout [float]? (optional)#

      Maximum time to wait for in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout().

Returns


RunAndWaitForWorkerAsync

Added in: v1.9 page.RunAndWaitForWorkerAsync

Performs action and waits for a new Worker. If predicate is provided, it passes Worker value into the predicate function and waits for predicate(worker) to return a truthy value. Will throw an error if the page is closed before the worker event is fired.

Usage

await Page.RunAndWaitForWorkerAsync(action, options);

Arguments

  • action Func<Task> Added in: v1.12#

    Action that triggers the event.

  • options PageRunAndWaitForWorkerOptions? (optional)

    • Predicate Func<Worker?, bool> (optional)#

      Receives the Worker object and resolves to truthy value when the waiting should resolve.

    • Timeout [float]? (optional)#

      Maximum time to wait for in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout().

Returns


WaitForWorkerAsync

Added in: v1.9 page.WaitForWorkerAsync

Performs action and waits for a new Worker. If predicate is provided, it passes Worker value into the predicate function and waits for predicate(worker) to return a truthy value. Will throw an error if the page is closed before the worker event is fired.

Usage

await Page.WaitForWorkerAsync(action, options);

Arguments

  • options PageRunAndWaitForWorkerOptions? (optional)
    • Predicate Func<Worker?, bool> (optional)#

      Receives the Worker object and resolves to truthy value when the waiting should resolve.

    • Timeout [float]? (optional)#

      Maximum time to wait for in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout().

Returns


ScreenshotAsync

Added before v1.9 page.ScreenshotAsync

Returns the buffer with the captured screenshot.

Usage

await Page.ScreenshotAsync(options);

Arguments

  • options PageScreenshotOptions? (optional)
    • Animations enum ScreenshotAnimations { Disabled, Allow }? (optional)#

      When set to "disabled", stops CSS animations, CSS transitions and Web Animations. Animations get different treatment depending on their duration:

      • finite animations are fast-forwarded to completion, so they'll fire transitionend event.
      • infinite animations are canceled to initial state, and then played over after the screenshot.

      Defaults to "allow" that leaves animations untouched.

    • Caret enum ScreenshotCaret { Hide, Initial }? (optional)#

      When set to "hide", screenshot will hide text caret. When set to "initial", text caret behavior will not be changed. Defaults to "hide".

    • Clip Clip? (optional)#

      • X [float]

        x-coordinate of top-left corner of clip area

      • Y [float]

        y-coordinate of top-left corner of clip area

      • Width [float]

        width of clipping area

      • Height [float]

        height of clipping area

      An object which specifies clipping of the resulting image.

    • FullPage bool? (optional)#

      When true, takes a screenshot of the full scrollable page, instead of the currently visible viewport. Defaults to false.

    • Mask IEnumerable?<Locator> (optional)#

      Specify locators that should be masked when the screenshot is taken. Masked elements will be overlaid with a pink box #FF00FF (customized by maskColor) that completely covers its bounding box.

    • MaskColor string? (optional) Added in: v1.35#

      Specify the color of the overlay box for masked elements, in CSS color format. Default color is pink #FF00FF.

    • OmitBackground bool? (optional)#

      Hides default white background and allows capturing screenshots with transparency. Not applicable to jpeg images. Defaults to false.

    • Path string? (optional)#

      The file path to save the image to. The screenshot type will be inferred from file extension. If path is a relative path, then it is resolved relative to the current working directory. If no path is provided, the image won't be saved to the disk.

    • Quality int? (optional)#

      The quality of the image, between 0-100. Not applicable to png images.

    • Scale enum ScreenshotScale { Css, Device }? (optional)#

      When set to "css", screenshot will have a single pixel per each css pixel on the page. For high-dpi devices, this will keep screenshots small. Using "device" option will produce a single pixel per each device pixel, so screenshots of high-dpi devices will be twice as large or even larger.

      Defaults to "device".

    • Style string? (optional) Added in: v1.41#

      Text of the stylesheet to apply while making the screenshot. This is where you can hide dynamic elements, make elements invisible or change their properties to help you creating repeatable screenshots. This stylesheet pierces the Shadow DOM and applies to the inner frames.

    • Timeout [float]? (optional)#

      Maximum time in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout() or Page.SetDefaultTimeout() methods.

    • Type enum ScreenshotType { Png, Jpeg }? (optional)#

      Specify screenshot type, defaults to png.

Returns


SetContentAsync

Added before v1.9 page.SetContentAsync

This method internally calls document.write(), inheriting all its specific characteristics and behaviors.

Usage

await Page.SetContentAsync(html, options);

Arguments

  • html string#

    HTML markup to assign to the page.

  • options PageSetContentOptions? (optional)

    • Timeout [float]? (optional)#

      Maximum operation time in milliseconds, defaults to 30 seconds, pass 0 to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultNavigationTimeout(), BrowserContext.SetDefaultTimeout(), Page.SetDefaultNavigationTimeout() or Page.SetDefaultTimeout() methods.

    • WaitUntil enum WaitUntilState { Load, DOMContentLoaded, NetworkIdle, Commit }? (optional)#

      When to consider operation succeeded, defaults to load. Events can be either:

      • 'domcontentloaded' - consider operation to be finished when the DOMContentLoaded event is fired.
      • 'load' - consider operation to be finished when the load event is fired.
      • 'networkidle' - DISCOURAGED consider operation to be finished when there are no network connections for at least 500 ms. Don't use this method for testing, rely on web assertions to assess readiness instead.
      • 'commit' - consider operation to be finished when network response is received and the document started loading.

Returns


SetDefaultNavigationTimeout

Added before v1.9 page.SetDefaultNavigationTimeout

This setting will change the default maximum navigation time for the following methods and related shortcuts:

Usage

Page.SetDefaultNavigationTimeout(timeout);

Arguments

  • timeout [float]#

    Maximum navigation time in milliseconds


SetDefaultTimeout

Added before v1.9 page.SetDefaultTimeout

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

Usage

Page.SetDefaultTimeout(timeout);

Arguments

  • timeout [float]#

    Maximum time in milliseconds


SetExtraHTTPHeadersAsync

Added before v1.9 page.SetExtraHTTPHeadersAsync

The extra HTTP headers will be sent with every request the page initiates.

note

Page.SetExtraHTTPHeadersAsync() does not guarantee the order of headers in the outgoing requests.

Usage

await Page.SetExtraHTTPHeadersAsync(headers);

Arguments

  • headers IDictionary<string, string>#

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

Returns


SetViewportSizeAsync

Added before v1.9 page.SetViewportSizeAsync

In the case of multiple pages in a single browser, each page can have its own viewport size. However, Browser.NewContextAsync() allows to set viewport size (and more) for all pages in the context at once.

Page.SetViewportSizeAsync() will resize the page. A lot of websites don't expect phones to change size, so you should set the viewport size before navigating to the page. Page.SetViewportSizeAsync() will also reset screen size, use Browser.NewContextAsync() with screen and viewport parameters if you need better control of these properties.

Usage

var page = await browser.NewPageAsync();
await page.SetViewportSizeAsync(640, 480);
await page.GotoAsync("https://www.microsoft.com");

Arguments

  • width int Added in: v1.10#
  • height int Added in: v1.10#

Returns


TitleAsync

Added before v1.9 page.TitleAsync

Returns the page's title.

Usage

await Page.TitleAsync();

Returns


UnrouteAsync

Added before v1.9 page.UnrouteAsync

Removes a route created with Page.RouteAsync(). When handler is not specified, removes all routes for the url.

Usage

await Page.UnrouteAsync(url, handler);

Arguments

  • url string | Regex | Func<string, bool>#

    A glob pattern, regex pattern or predicate receiving URL to match while routing.

  • handler Action<Route?> (optional)#

    Optional handler function to route the request.

Returns


UnrouteAllAsync

Added in: v1.41 page.UnrouteAllAsync

Removes all routes created with Page.RouteAsync() and Page.RouteFromHARAsync().

Usage

await Page.UnrouteAllAsync(options);

Arguments

  • options PageUnrouteAllOptions? (optional)
    • Behavior enum UnrouteBehavior { Wait, IgnoreErrors, Default }? (optional)#

      Specifies whether to wait for already running handlers and what to do if they throw errors:

      • 'default' - do not wait for current handler calls (if any) to finish, if unrouted handler throws, it may result in unhandled error
      • 'wait' - wait for current handler calls (if any) to finish
      • 'ignoreErrors' - do not wait for current handler calls (if any) to finish, all errors thrown by the handlers after unrouting are silently caught

Returns


Url

Added before v1.9 page.Url

Usage

Page.Url

Returns


Video

Added before v1.9 page.Video

Video object associated with this page.

Usage

Page.Video

Returns


ViewportSize

Added before v1.9 page.ViewportSize

Usage

Page.ViewportSize

Returns

  • ViewportSize?#
    • width int

      page width in pixels.

    • height int

      page height in pixels.


WaitForFunctionAsync

Added before v1.9 page.WaitForFunctionAsync

Returns when the expression returns a truthy value. It resolves to a JSHandle of the truthy value.

Usage

The Page.WaitForFunctionAsync() can be used to observe viewport size change:

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

class FrameExamples
{
public static async Task WaitForFunction()
{
using var playwright = await Playwright.CreateAsync();
await using var browser = await playwright.Webkit.LaunchAsync();
var page = await browser.NewPageAsync();
await page.SetViewportSizeAsync(50, 50);
await page.MainFrame.WaitForFunctionAsync("window.innerWidth < 100");
}
}

To pass an argument to the predicate of Page.WaitForFunctionAsync() function:

var selector = ".foo";
await page.WaitForFunctionAsync("selector => !!document.querySelector(selector)", selector);

Arguments

  • expression string#

    JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the function is automatically invoked.

  • arg EvaluationArgument? (optional)#

    Optional argument to pass to expression.

  • options PageWaitForFunctionOptions? (optional)

    • PollingInterval [float]? (optional)#

      If specified, then it is treated as an interval in milliseconds at which the function would be executed. By default if the option is not specified expression is executed in requestAnimationFrame callback.

    • Timeout [float]? (optional)#

      Maximum time to wait for in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout() or Page.SetDefaultTimeout() methods.

Returns


WaitForLoadStateAsync

Added before v1.9 page.WaitForLoadStateAsync

Returns when the required load state has been reached.

This resolves when the page reaches a required load state, load by default. The navigation must have been committed when this method is called. If current document has already reached the required state, resolves immediately.

note

Most of the time, this method is not needed because Playwright auto-waits before every action.

Usage

await page.GetByRole(AriaRole.Button).ClickAsync(); // Click triggers navigation.
await page.WaitForLoadStateAsync(); // The promise resolves after 'load' event.
var popup = await page.RunAndWaitForPopupAsync(async () =>
{
await page.GetByRole(AriaRole.Button).ClickAsync(); // click triggers the popup
});
// Wait for the "DOMContentLoaded" event.
await popup.WaitForLoadStateAsync(LoadState.DOMContentLoaded);
Console.WriteLine(await popup.TitleAsync()); // popup is ready to use.

Arguments

  • state enum LoadState { Load, DOMContentLoaded, NetworkIdle }? (optional)#

    Optional load state to wait for, defaults to load. If the state has been already reached while loading current document, the method resolves immediately. Can be one of:

    • 'load' - wait for the load event to be fired.
    • 'domcontentloaded' - wait for the DOMContentLoaded event to be fired.
    • 'networkidle' - DISCOURAGED wait until there are no network connections for at least 500 ms. Don't use this method for testing, rely on web assertions to assess readiness instead.
  • options PageWaitForLoadStateOptions? (optional)

Returns


WaitForURLAsync

Added in: v1.11 page.WaitForURLAsync

Waits for the main frame to navigate to the given URL.

Usage

await page.ClickAsync("a.delayed-navigation"); // clicking the link will indirectly cause a navigation
await page.WaitForURLAsync("**/target.html");

Arguments

  • url string | Regex | Func<string, bool>#

    A glob pattern, regex pattern or predicate receiving URL to match while waiting for the navigation. Note that if the parameter is a string without wildcard characters, the method will wait for navigation to URL that is exactly equal to the string.

  • options PageWaitForURLOptions? (optional)

    • Timeout [float]? (optional)#

      Maximum operation time in milliseconds, defaults to 30 seconds, pass 0 to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultNavigationTimeout(), BrowserContext.SetDefaultTimeout(), Page.SetDefaultNavigationTimeout() or Page.SetDefaultTimeout() methods.

    • WaitUntil enum WaitUntilState { Load, DOMContentLoaded, NetworkIdle, Commit }? (optional)#

      When to consider operation succeeded, defaults to load. Events can be either:

      • 'domcontentloaded' - consider operation to be finished when the DOMContentLoaded event is fired.
      • 'load' - consider operation to be finished when the load event is fired.
      • 'networkidle' - DISCOURAGED consider operation to be finished when there are no network connections for at least 500 ms. Don't use this method for testing, rely on web assertions to assess readiness instead.
      • 'commit' - consider operation to be finished when network response is received and the document started loading.

Returns


Workers

Added before v1.9 page.Workers

This method returns all of the dedicated WebWorkers associated with the page.

note

This does not contain ServiceWorkers

Usage

Page.Workers

Returns


Properties

APIRequest

Added in: v1.16 page.APIRequest

API testing helper associated with this page. This method returns the same instance as BrowserContext.APIRequest on the page's context. See BrowserContext.APIRequest for more details.

Usage

Page.APIRequest

Type


Clock

Added in: v1.45 page.Clock

Playwright has ability to mock clock and passage of time.

Usage

Page.Clock

Type


Keyboard

Added before v1.9 page.Keyboard

Usage

Page.Keyboard

Type


Mouse

Added before v1.9 page.Mouse

Usage

Page.Mouse

Type


Touchscreen

Added before v1.9 page.Touchscreen

Usage

Page.Touchscreen

Type


Events

event Close

Added before v1.9 page.event Close

Emitted when the page closes.

Usage

Page.Close += async (_, page) => {};

Event data


event Console

Added before v1.9 page.event 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 are available on the ConsoleMessage event handler argument.

Usage

page.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 data


event Crash

Added before v1.9 page.event Crash

Emitted when the page crashes. Browser pages might crash if they try to allocate too much memory. When the page crashes, ongoing and subsequent operations will throw.

The most common way to deal with crashes is to catch an exception:

try {
// Crash might happen during a click.
await page.ClickAsync("button");
// Or while waiting for an event.
await page.WaitForPopup();
} catch (PlaywrightException e) {
// When the page crashes, exception message contains "crash".
}

Usage

Page.Crash += async (_, page) => {};

Event data


event Dialog

Added before v1.9 page.event Dialog

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

Usage

page.RequestFailed += (_, request) =>
{
Console.WriteLine(request.Url + " " + request.Failure);
};
note

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

Event data


event DOMContentLoaded

Added in: v1.9 page.event DOMContentLoaded

Emitted when the JavaScript DOMContentLoaded event is dispatched.

Usage

Page.DOMContentLoaded += async (_, page) => {};

Event data


event Download

Added before v1.9 page.event Download

Emitted when attachment download started. User can access basic file operations on downloaded content via the passed Download instance.

Usage

Page.Download += async (_, download) => {};

Event data


event FileChooser

Added in: v1.9 page.event FileChooser

Emitted when a file chooser is supposed to appear, such as after clicking the <input type=file>. Playwright can respond to it via setting the input files using FileChooser.SetFilesAsync() that can be uploaded after that.

page.FileChooser += (_, fileChooser) =>
{
fileChooser.SetFilesAsync(@"C:\temp\myfile.pdf");
};

Usage

Page.FileChooser += async (_, fileChooser) => {};

Event data


event FrameAttached

Added in: v1.9 page.event FrameAttached

Emitted when a frame is attached.

Usage

Page.FrameAttached += async (_, frame) => {};

Event data


event FrameDetached

Added in: v1.9 page.event FrameDetached

Emitted when a frame is detached.

Usage

Page.FrameDetached += async (_, frame) => {};

Event data


event FrameNavigated

Added in: v1.9 page.event FrameNavigated

Emitted when a frame is navigated to a new url.

Usage

Page.FrameNavigated += async (_, frame) => {};

Event data


event Load

Added before v1.9 page.event Load

Emitted when the JavaScript load event is dispatched.

Usage

Page.Load += async (_, page) => {};

Event data


event PageError

Added in: v1.9 page.event PageError

Emitted when an uncaught exception happens within the page.

// Log all uncaught errors to the terminal
page.PageError += (_, exception) =>
{
Console.WriteLine("Uncaught exception: " + exception);
};

Usage

Page.PageError += async (_, value) => {};

Event data


event Popup

Added before v1.9 page.event Popup

Emitted when the page opens a new tab or window. This event is emitted in addition to the BrowserContext.Page, but only for popups relevant to this 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 BrowserContext.RouteAsync() and BrowserContext.Request respectively instead of similar methods on the Page.

var popup = await page.RunAndWaitForPopupAsync(async () =>
{
await page.GetByText("open the popup").ClickAsync();
});
Console.WriteLine(await popup.EvaluateAsync<string>("location.href"));
note

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

Usage

Page.Popup += async (_, page) => {};

Event data


event Request

Added before v1.9 page.event Request

Emitted when a page issues a request. The request object is read-only. In order to intercept and mutate requests, see Page.RouteAsync() or BrowserContext.RouteAsync().

Usage

Page.Request += async (_, request) => {};

Event data


event RequestFailed

Added in: v1.9 page.event RequestFailed

Emitted when a request fails, for example by timing out.

note

HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request will complete with Page.RequestFinished event and not with Page.RequestFailed. A request will only be considered failed when the client cannot get an HTTP response from the server, e.g. due to network error net::ERR_FAILED.

Usage

Page.RequestFailed += async (_, request) => {};

Event data


event RequestFinished

Added in: v1.9 page.event 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.

Usage

Page.RequestFinished += async (_, request) => {};

Event data


event Response

Added before v1.9 page.event Response

Emitted when response status and headers are received for a request. For a successful response, the sequence of events is request, response and requestfinished.

Usage

Page.Response += async (_, response) => {};

Event data


event WebSocket

Added in: v1.9 page.event WebSocket

Emitted when WebSocket request is sent.

Usage

Page.WebSocket += async (_, webSocket) => {};

Event data


event Worker

Added before v1.9 page.event Worker

Emitted when a dedicated WebWorker is spawned by the page.

Usage

Page.Worker += async (_, worker) => {};

Event data


Deprecated

Accessibility

Added before v1.9 page.Accessibility
Deprecated

This property is discouraged. Please use other libraries such as Axe if you need to test page accessibility. See our Node.js guide for integration with Axe.

Usage

Page.Accessibility

Type


CheckAsync

Added before v1.9 page.CheckAsync
Discouraged

Use locator-based Locator.CheckAsync() instead. Read more about locators.

This method checks an element matching selector by performing the following steps:

  1. Find an element matching selector. If there is none, wait until a matching element is attached to the DOM.
  2. Ensure that matched element is a checkbox or a radio input. If not, this method throws. If the element is already checked, this method returns immediately.
  3. Wait for actionability checks on the matched element, unless force option is set. If the element is detached during the checks, the whole action is retried.
  4. Scroll the element into view if needed.
  5. Use Page.Mouse to click in the center of the element.
  6. Ensure that the element is now checked. If not, this method throws.

When all steps combined have not finished during the specified timeout, this method throws a TimeoutError. Passing zero timeout disables this.

Usage

await Page.CheckAsync(selector, options);

Arguments

  • selector string#

    A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

  • options PageCheckOptions? (optional)

    • Force bool? (optional)#

      Whether to bypass the actionability checks. Defaults to false.

    • NoWaitAfter bool? (optional)#

      Deprecated

      This option has no effect.

      This option has no effect.

    • Position Position? (optional) Added in: v1.11#

      • X [float]

      • Y [float]

      A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of the element.

    • Strict bool? (optional) Added in: v1.14#

      When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

    • Timeout [float]? (optional)#

      Maximum time in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout() or Page.SetDefaultTimeout() methods.

    • Trial bool? (optional) Added in: v1.11#

      When set, this method only performs the actionability checks and skips the action. Defaults to false. Useful to wait until the element is ready for the action without performing it.

Returns


ClickAsync

Added before v1.9 page.ClickAsync
Discouraged

Use locator-based Locator.ClickAsync() instead. Read more about locators.

This method clicks an element matching selector by performing the following steps:

  1. Find an element matching selector. If there is none, wait until a matching element is attached to the DOM.
  2. Wait for actionability checks on the matched element, unless force option is set. If the element is detached during the checks, the whole action is retried.
  3. Scroll the element into view if needed.
  4. Use Page.Mouse to click in the center of the element, or the specified position.
  5. Wait for initiated navigations to either succeed or fail, unless noWaitAfter option is set.

When all steps combined have not finished during the specified timeout, this method throws a TimeoutError. Passing zero timeout disables this.

Usage

await Page.ClickAsync(selector, options);

Arguments

  • selector string#

    A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

  • options PageClickOptions? (optional)

    • Button enum MouseButton { Left, Right, Middle }? (optional)#

      Defaults to left.

    • ClickCount int? (optional)#

      defaults to 1. See UIEvent.detail.

    • Delay [float]? (optional)#

      Time to wait between mousedown and mouseup in milliseconds. Defaults to 0.

    • Force bool? (optional)#

      Whether to bypass the actionability checks. Defaults to false.

    • Modifiers IEnumerable?<enum KeyboardModifier { Alt, Control, ControlOrMeta, Meta, Shift }> (optional)#

      Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to "Control" on Windows and Linux and to "Meta" on macOS.

    • NoWaitAfter bool? (optional)#

      Deprecated

      This option will default to true in the future.

      Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to false.

    • Position Position? (optional)#

      • X [float]

      • Y [float]

      A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of the element.

    • Strict bool? (optional) Added in: v1.14#

      When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

    • Timeout [float]? (optional)#

      Maximum time in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout() or Page.SetDefaultTimeout() methods.

    • Trial bool? (optional) Added in: v1.11#

      When set, this method only performs the actionability checks and skips the action. Defaults to false. Useful to wait until the element is ready for the action without performing it.

Returns


DblClickAsync

Added before v1.9 page.DblClickAsync
Discouraged

Use locator-based Locator.DblClickAsync() instead. Read more about locators.

This method double clicks an element matching selector by performing the following steps:

  1. Find an element matching selector. If there is none, wait until a matching element is attached to the DOM.
  2. Wait for actionability checks on the matched element, unless force option is set. If the element is detached during the checks, the whole action is retried.
  3. Scroll the element into view if needed.
  4. Use Page.Mouse to double click in the center of the element, or the specified position.

When all steps combined have not finished during the specified timeout, this method throws a TimeoutError. Passing zero timeout disables this.

note

page.dblclick() dispatches two click events and a single dblclick event.

Usage

await Page.DblClickAsync(selector, options);

Arguments

  • selector string#

    A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

  • options PageDblClickOptions? (optional)

    • Button enum MouseButton { Left, Right, Middle }? (optional)#

      Defaults to left.

    • Delay [float]? (optional)#

      Time to wait between mousedown and mouseup in milliseconds. Defaults to 0.

    • Force bool? (optional)#

      Whether to bypass the actionability checks. Defaults to false.

    • Modifiers IEnumerable?<enum KeyboardModifier { Alt, Control, ControlOrMeta, Meta, Shift }> (optional)#

      Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to "Control" on Windows and Linux and to "Meta" on macOS.

    • NoWaitAfter bool? (optional)#

      Deprecated

      This option has no effect.

      This option has no effect.

    • Position Position? (optional)#

      • X [float]

      • Y [float]

      A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of the element.

    • Strict bool? (optional) Added in: v1.14#

      When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

    • Timeout [float]? (optional)#

      Maximum time in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout() or Page.SetDefaultTimeout() methods.

    • Trial bool? (optional) Added in: v1.11#

      When set, this method only performs the actionability checks and skips the action. Defaults to false. Useful to wait until the element is ready for the action without performing it.

Returns


DispatchEventAsync

Added before v1.9 page.DispatchEventAsync
Discouraged

Use locator-based Locator.DispatchEventAsync() instead. Read more about locators.

The snippet below dispatches the click event on the element. Regardless of the visibility state of the element, click is dispatched. This is equivalent to calling element.click().

Usage

await page.DispatchEventAsync("button#submit", "click");

Under the hood, it creates an instance of an event based on the given type, initializes it with eventInit properties and dispatches it on the element. Events are composed, cancelable and bubble by default.

Since eventInit is event-specific, please refer to the events documentation for the lists of initial properties:

You can also specify JSHandle as the property value if you want live objects to be passed into the event:

var dataTransfer = await page.EvaluateHandleAsync("() => new DataTransfer()");
await page.DispatchEventAsync("#source", "dragstart", new { dataTransfer });

Arguments

  • selector string#

    A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

  • type string#

    DOM event type: "click", "dragstart", etc.

  • eventInit EvaluationArgument? (optional)#

    Optional event-specific initialization properties.

  • options PageDispatchEventOptions? (optional)

    • Strict bool? (optional) Added in: v1.14#

      When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

    • Timeout [float]? (optional)#

      Maximum time in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout() or Page.SetDefaultTimeout() methods.

Returns


EvalOnSelectorAsync

Added in: v1.9 page.EvalOnSelectorAsync
Discouraged

This method does not wait for the element to pass actionability checks and therefore can lead to the flaky tests. Use Locator.EvaluateAsync(), other Locator helper methods or web-first assertions instead.

The method finds an element matching the specified selector within the page and passes it as a first argument to expression. If no elements match the selector, the method throws an error. Returns the value of expression.

If expression returns a Promise, then Page.EvalOnSelectorAsync() would wait for the promise to resolve and return its value.

Usage

var searchValue = await page.EvalOnSelectorAsync<string>("#search", "el => el.value");
var preloadHref = await page.EvalOnSelectorAsync<string>("link[rel=preload]", "el => el.href");
var html = await page.EvalOnSelectorAsync(".main-container", "(e, suffix) => e.outerHTML + suffix", "hello");

Arguments

  • selector string#

    A selector to query for.

  • expression string#

    JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the function is automatically invoked.

  • arg EvaluationArgument? (optional)#

    Optional argument to pass to expression.

  • options PageEvalOnSelectorOptions? (optional)

    • Strict bool? (optional) Added in: v1.14#

      When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

Returns

  • [object]#

EvalOnSelectorAllAsync

Added in: v1.9 page.EvalOnSelectorAllAsync
Discouraged

In most cases, Locator.EvaluateAllAsync(), other Locator helper methods and web-first assertions do a better job.

The method finds all elements matching the specified selector within the page and passes an array of matched elements as a first argument to expression. Returns the result of expression invocation.

If expression returns a Promise, then Page.EvalOnSelectorAllAsync() would wait for the promise to resolve and return its value.

Usage

var divsCount = await page.EvalOnSelectorAllAsync<bool>("div", "(divs, min) => divs.length >= min", 10);

Arguments

  • selector string#

    A selector to query for.

  • expression string#

    JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the function is automatically invoked.

  • arg EvaluationArgument? (optional)#

    Optional argument to pass to expression.

Returns

  • [object]#

FillAsync

Added before v1.9 page.FillAsync
Discouraged

Use locator-based Locator.FillAsync() instead. Read more about locators.

This method waits for an element matching selector, waits for actionability checks, focuses the element, fills it and triggers an input event after filling. Note that you can pass an empty string to clear the input field.

If the target element is not an <input>, <textarea> or [contenteditable] element, this method throws an error. However, if the element is inside the <label> element that has an associated control, the control will be filled instead.

To send fine-grained keyboard events, use Locator.PressSequentiallyAsync().

Usage

await Page.FillAsync(selector, value, options);

Arguments

  • selector string#

    A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

  • value string#

    Value to fill for the <input>, <textarea> or [contenteditable] element.

  • options PageFillOptions? (optional)

    • Force bool? (optional) Added in: v1.13#

      Whether to bypass the actionability checks. Defaults to false.

    • NoWaitAfter bool? (optional)#

      Deprecated

      This option has no effect.

      This option has no effect.

    • Strict bool? (optional) Added in: v1.14#

      When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

    • Timeout [float]? (optional)#

      Maximum time in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout() or Page.SetDefaultTimeout() methods.

Returns


FocusAsync

Added before v1.9 page.FocusAsync
Discouraged

Use locator-based Locator.FocusAsync() instead. Read more about locators.

This method fetches an element with selector and focuses it. If there's no element matching selector, the method waits until a matching element appears in the DOM.

Usage

await Page.FocusAsync(selector, options);

Arguments

  • selector string#

    A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

  • options PageFocusOptions? (optional)

    • Strict bool? (optional) Added in: v1.14#

      When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

    • Timeout [float]? (optional)#

      Maximum time in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout() or Page.SetDefaultTimeout() methods.

Returns


GetAttributeAsync

Added before v1.9 page.GetAttributeAsync
Discouraged

Use locator-based Locator.GetAttributeAsync() instead. Read more about locators.

Returns element attribute value.

Usage

await Page.GetAttributeAsync(selector, name, options);

Arguments

  • selector string#

    A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

  • name string#

    Attribute name to get the value for.

  • options PageGetAttributeOptions? (optional)

    • Strict bool? (optional) Added in: v1.14#

      When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

    • Timeout [float]? (optional)#

      Maximum time in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout() or Page.SetDefaultTimeout() methods.

Returns


HoverAsync

Added before v1.9 page.HoverAsync
Discouraged

Use locator-based Locator.HoverAsync() instead. Read more about locators.

This method hovers over an element matching selector by performing the following steps:

  1. Find an element matching selector. If there is none, wait until a matching element is attached to the DOM.
  2. Wait for actionability checks on the matched element, unless force option is set. If the element is detached during the checks, the whole action is retried.
  3. Scroll the element into view if needed.
  4. Use Page.Mouse to hover over the center of the element, or the specified position.

When all steps combined have not finished during the specified timeout, this method throws a TimeoutError. Passing zero timeout disables this.

Usage

await Page.HoverAsync(selector, options);

Arguments

  • selector string#

    A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

  • options PageHoverOptions? (optional)

    • Force bool? (optional)#

      Whether to bypass the actionability checks. Defaults to false.

    • Modifiers IEnumerable?<enum KeyboardModifier { Alt, Control, ControlOrMeta, Meta, Shift }> (optional)#

      Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to "Control" on Windows and Linux and to "Meta" on macOS.

    • NoWaitAfter bool? (optional) Added in: v1.28#

      Deprecated

      This option has no effect.

      This option has no effect.

    • Position Position? (optional)#

      • X [float]

      • Y [float]

      A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of the element.

    • Strict bool? (optional) Added in: v1.14#

      When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

    • Timeout [float]? (optional)#

      Maximum time in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout() or Page.SetDefaultTimeout() methods.

    • Trial bool? (optional) Added in: v1.11#

      When set, this method only performs the actionability checks and skips the action. Defaults to false. Useful to wait until the element is ready for the action without performing it.

Returns


InnerHTMLAsync

Added before v1.9 page.InnerHTMLAsync
Discouraged

Use locator-based Locator.InnerHTMLAsync() instead. Read more about locators.

Returns element.innerHTML.

Usage

await Page.InnerHTMLAsync(selector, options);

Arguments

  • selector string#

    A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

  • options PageInnerHTMLOptions? (optional)

    • Strict bool? (optional) Added in: v1.14#

      When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

    • Timeout [float]? (optional)#

      Maximum time in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout() or Page.SetDefaultTimeout() methods.

Returns


InnerTextAsync

Added before v1.9 page.InnerTextAsync
Discouraged

Use locator-based Locator.InnerTextAsync() instead. Read more about locators.

Returns element.innerText.

Usage

await Page.InnerTextAsync(selector, options);

Arguments

  • selector string#

    A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

  • options PageInnerTextOptions? (optional)

    • Strict bool? (optional) Added in: v1.14#

      When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

    • Timeout [float]? (optional)#

      Maximum time in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout() or Page.SetDefaultTimeout() methods.

Returns


InputValueAsync

Added in: v1.13 page.InputValueAsync
Discouraged

Use locator-based Locator.InputValueAsync() instead. Read more about locators.

Returns input.value for the selected <input> or <textarea> or <select> element.

Throws for non-input elements. However, if the element is inside the <label> element that has an associated control, returns the value of the control.

Usage

await Page.InputValueAsync(selector, options);

Arguments

  • selector string#

    A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

  • options PageInputValueOptions? (optional)

    • Strict bool? (optional) Added in: v1.14#

      When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

    • Timeout [float]? (optional)#

      Maximum time in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout() or Page.SetDefaultTimeout() methods.

Returns


IsCheckedAsync

Added before v1.9 page.IsCheckedAsync
Discouraged

Use locator-based Locator.IsCheckedAsync() instead. Read more about locators.

Returns whether the element is checked. Throws if the element is not a checkbox or radio input.

Usage

await Page.IsCheckedAsync(selector, options);

Arguments

  • selector string#

    A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

  • options PageIsCheckedOptions? (optional)

    • Strict bool? (optional) Added in: v1.14#

      When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

    • Timeout [float]? (optional)#

      Maximum time in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout() or Page.SetDefaultTimeout() methods.

Returns


IsDisabledAsync

Added before v1.9 page.IsDisabledAsync
Discouraged

Use locator-based Locator.IsDisabledAsync() instead. Read more about locators.

Returns whether the element is disabled, the opposite of enabled.

Usage

await Page.IsDisabledAsync(selector, options);

Arguments

  • selector string#

    A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

  • options PageIsDisabledOptions? (optional)

    • Strict bool? (optional) Added in: v1.14#

      When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

    • Timeout [float]? (optional)#

      Maximum time in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout() or Page.SetDefaultTimeout() methods.

Returns


IsEditableAsync

Added before v1.9 page.IsEditableAsync
Discouraged

Use locator-based Locator.IsEditableAsync() instead. Read more about locators.

Returns whether the element is editable.

Usage

await Page.IsEditableAsync(selector, options);

Arguments

  • selector string#

    A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

  • options PageIsEditableOptions? (optional)

    • Strict bool? (optional) Added in: v1.14#

      When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

    • Timeout [float]? (optional)#

      Maximum time in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout() or Page.SetDefaultTimeout() methods.

Returns


IsEnabledAsync

Added before v1.9 page.IsEnabledAsync
Discouraged

Use locator-based Locator.IsEnabledAsync() instead. Read more about locators.

Returns whether the element is enabled.

Usage

await Page.IsEnabledAsync(selector, options);

Arguments

  • selector string#

    A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

  • options PageIsEnabledOptions? (optional)

    • Strict bool? (optional) Added in: v1.14#

      When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

    • Timeout [float]? (optional)#

      Maximum time in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout() or Page.SetDefaultTimeout() methods.

Returns


IsHiddenAsync

Added before v1.9 page.IsHiddenAsync
Discouraged

Use locator-based Locator.IsHiddenAsync() instead. Read more about locators.

Returns whether the element is hidden, the opposite of visible. selector that does not match any elements is considered hidden.

Usage

await Page.IsHiddenAsync(selector, options);

Arguments

  • selector string#

    A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

  • options PageIsHiddenOptions? (optional)

    • Strict bool? (optional) Added in: v1.14#

      When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

    • Timeout [float]? (optional)#

      Deprecated

      This option is ignored. Page.IsHiddenAsync() does not wait for the element to become hidden and returns immediately.

Returns


IsVisibleAsync

Added before v1.9 page.IsVisibleAsync
Discouraged

Use locator-based Locator.IsVisibleAsync() instead. Read more about locators.

Returns whether the element is visible. selector that does not match any elements is considered not visible.

Usage

await Page.IsVisibleAsync(selector, options);

Arguments

  • selector string#

    A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

  • options PageIsVisibleOptions? (optional)

    • Strict bool? (optional) Added in: v1.14#

      When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

    • Timeout [float]? (optional)#

      Deprecated

      This option is ignored. Page.IsVisibleAsync() does not wait for the element to become visible and returns immediately.

Returns


PressAsync

Added before v1.9 page.PressAsync
Discouraged

Use locator-based Locator.PressAsync() instead. Read more about locators.

Focuses the element, and then uses Keyboard.DownAsync() and Keyboard.UpAsync().

key can specify the intended keyboardEvent.key value or a single character to generate the text for. A superset of the key values can be found here. Examples of the keys are:

F1 - F12, Digit0- Digit9, KeyA- KeyZ, Backquote, Minus, Equal, Backslash, Backspace, Tab, Delete, Escape, ArrowDown, End, Enter, Home, Insert, PageDown, PageUp, ArrowRight, ArrowUp, etc.

Following modification shortcuts are also supported: Shift, Control, Alt, Meta, ShiftLeft, ControlOrMeta. ControlOrMeta resolves to Control on Windows and Linux and to Meta on macOS.

Holding down Shift will type the text that corresponds to the key in the upper case.

If key is a single character, it is case-sensitive, so the values a and A will generate different respective texts.

Shortcuts such as key: "Control+o", key: "Control++ or key: "Control+Shift+T" are supported as well. When specified with the modifier, modifier is pressed and being held while the subsequent key is being pressed.

Usage

var page = await browser.NewPageAsync();
await page.GotoAsync("https://keycode.info");
await page.PressAsync("body", "A");
await page.ScreenshotAsync(new() { Path = "A.png" });
await page.PressAsync("body", "ArrowLeft");
await page.ScreenshotAsync(new() { Path = "ArrowLeft.png" });
await page.PressAsync("body", "Shift+O");
await page.ScreenshotAsync(new() { Path = "O.png" });

Arguments

  • selector string#

    A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

  • key string#

    Name of the key to press or a character to generate, such as ArrowLeft or a.

  • options PagePressOptions? (optional)

    • Delay [float]? (optional)#

      Time to wait between keydown and keyup in milliseconds. Defaults to 0.

    • NoWaitAfter bool? (optional)#

      Deprecated

      This option will default to true in the future.

      Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to false.

    • Strict bool? (optional) Added in: v1.14#

      When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

    • Timeout [float]? (optional)#

      Maximum time in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout() or Page.SetDefaultTimeout() methods.

Returns


QuerySelectorAsync

Added in: v1.9 page.QuerySelectorAsync
Discouraged

Use locator-based Page.Locator() instead. Read more about locators.

The method finds an element matching the specified selector within the page. If no elements match the selector, the return value resolves to null. To wait for an element on the page, use Locator.WaitForAsync().

Usage

await Page.QuerySelectorAsync(selector, options);

Arguments

  • selector string#

    A selector to query for.

  • options PageQuerySelectorOptions? (optional)

    • Strict bool? (optional) Added in: v1.14#

      When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

Returns


QuerySelectorAllAsync

Added in: v1.9 page.QuerySelectorAllAsync
Discouraged

Use locator-based Page.Locator() instead. Read more about locators.

The method finds all elements matching the specified selector within the page. If no elements match the selector, the return value resolves to [].

Usage

await Page.QuerySelectorAllAsync(selector);

Arguments

  • selector string#

    A selector to query for.

Returns


RunAndWaitForNavigationAsync

Added before v1.9 page.RunAndWaitForNavigationAsync
Deprecated

This method is inherently racy, please use Page.WaitForURLAsync() instead.

Waits for the main frame navigation and returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. In case of navigation to a different anchor or navigation due to History API usage, the navigation will resolve with null.

Usage

This resolves when the page navigates to a new URL or reloads. It is useful for when you run code which will indirectly cause the page to navigate. e.g. The click target has an onclick handler that triggers navigation from a setTimeout. Consider this example:

await page.RunAndWaitForNavigationAsync(async () =>
{
// This action triggers the navigation after a timeout.
await page.GetByText("Navigate after timeout").ClickAsync();
});

// The method continues after navigation has finished
note

Usage of the History API to change the URL is considered a navigation.

Arguments

  • action Func<Task> Added in: v1.12#

    Action that triggers the event.

  • options PageRunAndWaitForNavigationOptions? (optional)

    • Timeout [float]? (optional)#

      Maximum operation time in milliseconds, defaults to 30 seconds, pass 0 to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultNavigationTimeout(), BrowserContext.SetDefaultTimeout(), Page.SetDefaultNavigationTimeout() or Page.SetDefaultTimeout() methods.

    • Url|UrlRegex|UrlFunc string? | Regex? | Func<string?, bool> (optional)#

      A glob pattern, regex pattern or predicate receiving URL to match while waiting for the navigation. Note that if the parameter is a string without wildcard characters, the method will wait for navigation to URL that is exactly equal to the string.

    • WaitUntil enum WaitUntilState { Load, DOMContentLoaded, NetworkIdle, Commit }? (optional)#

      When to consider operation succeeded, defaults to load. Events can be either:

      • 'domcontentloaded' - consider operation to be finished when the DOMContentLoaded event is fired.
      • 'load' - consider operation to be finished when the load event is fired.
      • 'networkidle' - DISCOURAGED consider operation to be finished when there are no network connections for at least 500 ms. Don't use this method for testing, rely on web assertions to assess readiness instead.
      • 'commit' - consider operation to be finished when network response is received and the document started loading.

Returns


WaitForNavigationAsync

Added before v1.9 page.WaitForNavigationAsync
Deprecated

This method is inherently racy, please use Page.WaitForURLAsync() instead.

Waits for the main frame navigation and returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. In case of navigation to a different anchor or navigation due to History API usage, the navigation will resolve with null.

Usage

This resolves when the page navigates to a new URL or reloads. It is useful for when you run code which will indirectly cause the page to navigate. e.g. The click target has an onclick handler that triggers navigation from a setTimeout. Consider this example:

await page.RunAndWaitForNavigationAsync(async () =>
{
// This action triggers the navigation after a timeout.
await page.GetByText("Navigate after timeout").ClickAsync();
});

// The method continues after navigation has finished
note

Usage of the History API to change the URL is considered a navigation.

Arguments

  • options PageRunAndWaitForNavigationOptions? (optional)
    • Timeout [float]? (optional)#

      Maximum operation time in milliseconds, defaults to 30 seconds, pass 0 to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultNavigationTimeout(), BrowserContext.SetDefaultTimeout(), Page.SetDefaultNavigationTimeout() or Page.SetDefaultTimeout() methods.

    • Url|UrlRegex|UrlFunc string? | Regex? | Func<string?, bool> (optional)#

      A glob pattern, regex pattern or predicate receiving URL to match while waiting for the navigation. Note that if the parameter is a string without wildcard characters, the method will wait for navigation to URL that is exactly equal to the string.

    • WaitUntil enum WaitUntilState { Load, DOMContentLoaded, NetworkIdle, Commit }? (optional)#

      When to consider operation succeeded, defaults to load. Events can be either:

      • 'domcontentloaded' - consider operation to be finished when the DOMContentLoaded event is fired.
      • 'load' - consider operation to be finished when the load event is fired.
      • 'networkidle' - DISCOURAGED consider operation to be finished when there are no network connections for at least 500 ms. Don't use this method for testing, rely on web assertions to assess readiness instead.
      • 'commit' - consider operation to be finished when network response is received and the document started loading.

Returns


SelectOptionAsync

Added before v1.9 page.SelectOptionAsync
Discouraged

Use locator-based Locator.SelectOptionAsync() instead. Read more about locators.

This method waits for an element matching selector, waits for actionability checks, waits until all specified options are present in the <select> element and selects these options.

If the target element is not a <select> element, this method throws an error. However, if the element is inside the <label> element that has an associated control, the control will be used instead.

Returns the array of option values that have been successfully selected.

Triggers a change and input event once all the provided options have been selected.

Usage

// Single selection matching the value or label
await page.SelectOptionAsync("select#colors", new[] { "blue" });
// single selection matching both the value and the label
await page.SelectOptionAsync("select#colors", new[] { new SelectOptionValue() { Label = "blue" } });
// multiple
await page.SelectOptionAsync("select#colors", new[] { "red", "green", "blue" });

Arguments

  • selector string#

    A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

  • values string? | ElementHandle? | IEnumerable?<string> | SelectOption | IEnumerable?<ElementHandle> | IEnumerable?<SelectOption>#

    • Value string? (optional)

      Matches by option.value. Optional.

    • Label string? (optional)

      Matches by option.label. Optional.

    • Index int? (optional)

      Matches by the index. Optional.

    Options to select. If the <select> has the multiple attribute, all matching options are selected, otherwise only the first option matching one of the passed options is selected. String values are matching both values and labels. Option is considered matching if all specified properties match.

  • options PageSelectOptionOptions? (optional)

    • Force bool? (optional) Added in: v1.13#

      Whether to bypass the actionability checks. Defaults to false.

    • NoWaitAfter bool? (optional)#

      Deprecated

      This option has no effect.

      This option has no effect.

    • Strict bool? (optional) Added in: v1.14#

      When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

    • Timeout [float]? (optional)#

      Maximum time in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout() or Page.SetDefaultTimeout() methods.

Returns


SetCheckedAsync

Added in: v1.15 page.SetCheckedAsync
Discouraged

Use locator-based Locator.SetCheckedAsync() instead. Read more about locators.

This method checks or unchecks an element matching selector by performing the following steps:

  1. Find an element matching selector. If there is none, wait until a matching element is attached to the DOM.
  2. Ensure that matched element is a checkbox or a radio input. If not, this method throws.
  3. If the element already has the right checked state, this method returns immediately.
  4. Wait for actionability checks on the matched element, unless force option is set. If the element is detached during the checks, the whole action is retried.
  5. Scroll the element into view if needed.
  6. Use Page.Mouse to click in the center of the element.
  7. Ensure that the element is now checked or unchecked. If not, this method throws.

When all steps combined have not finished during the specified timeout, this method throws a TimeoutError. Passing zero timeout disables this.

Usage

await Page.SetCheckedAsync(selector, checked, options);

Arguments

  • selector string#

    A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

  • checkedState bool#

    Whether to check or uncheck the checkbox.

  • options PageSetCheckedOptions? (optional)

    • Force bool? (optional)#

      Whether to bypass the actionability checks. Defaults to false.

    • NoWaitAfter bool? (optional)#

      Deprecated

      This option has no effect.

      This option has no effect.

    • Position Position? (optional)#

      • X [float]

      • Y [float]

      A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of the element.

    • Strict bool? (optional)#

      When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

    • Timeout [float]? (optional)#

      Maximum time in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout() or Page.SetDefaultTimeout() methods.

    • Trial bool? (optional)#

      When set, this method only performs the actionability checks and skips the action. Defaults to false. Useful to wait until the element is ready for the action without performing it.

Returns


SetInputFilesAsync

Added before v1.9 page.SetInputFilesAsync
Discouraged

Use locator-based Locator.SetInputFilesAsync() instead. Read more about locators.

Sets the value of the file input to these file paths or files. If some of the filePaths are relative paths, then they are resolved relative to the current working directory. For empty array, clears the selected files. For inputs with a [webkitdirectory] attribute, only a single directory path is supported.

This method expects selector to point to an input element. However, if the element is inside the <label> element that has an associated control, targets the control instead.

Usage

await Page.SetInputFilesAsync(selector, files, options);

Arguments

  • selector string#

    A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

  • files string | IEnumerable<string> | FilePayload | IEnumerable<FilePayload>#

  • options PageSetInputFilesOptions? (optional)

    • NoWaitAfter bool? (optional)#

      Deprecated

      This option has no effect.

      This option has no effect.

    • Strict bool? (optional) Added in: v1.14#

      When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

    • Timeout [float]? (optional)#

      Maximum time in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout() or Page.SetDefaultTimeout() methods.

Returns


TapAsync

Added before v1.9 page.TapAsync
Discouraged

Use locator-based Locator.TapAsync() instead. Read more about locators.

This method taps an element matching selector by performing the following steps:

  1. Find an element matching selector. If there is none, wait until a matching element is attached to the DOM.
  2. Wait for actionability checks on the matched element, unless force option is set. If the element is detached during the checks, the whole action is retried.
  3. Scroll the element into view if needed.
  4. Use Page.Touchscreen to tap the center of the element, or the specified position.

When all steps combined have not finished during the specified timeout, this method throws a TimeoutError. Passing zero timeout disables this.

note

Page.TapAsync() the method will throw if hasTouch option of the browser context is false.

Usage

await Page.TapAsync(selector, options);

Arguments

  • selector string#

    A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

  • options PageTapOptions? (optional)

    • Force bool? (optional)#

      Whether to bypass the actionability checks. Defaults to false.

    • Modifiers IEnumerable?<enum KeyboardModifier { Alt, Control, ControlOrMeta, Meta, Shift }> (optional)#

      Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to "Control" on Windows and Linux and to "Meta" on macOS.

    • NoWaitAfter bool? (optional)#

      Deprecated

      This option has no effect.

      This option has no effect.

    • Position Position? (optional)#

      • X [float]

      • Y [float]

      A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of the element.

    • Strict bool? (optional) Added in: v1.14#

      When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

    • Timeout [float]? (optional)#

      Maximum time in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout() or Page.SetDefaultTimeout() methods.

    • Trial bool? (optional) Added in: v1.11#

      When set, this method only performs the actionability checks and skips the action. Defaults to false. Useful to wait until the element is ready for the action without performing it.

Returns


TextContentAsync

Added before v1.9 page.TextContentAsync
Discouraged

Use locator-based Locator.TextContentAsync() instead. Read more about locators.

Returns element.textContent.

Usage

await Page.TextContentAsync(selector, options);

Arguments

  • selector string#

    A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

  • options PageTextContentOptions? (optional)

    • Strict bool? (optional) Added in: v1.14#

      When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

    • Timeout [float]? (optional)#

      Maximum time in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout() or Page.SetDefaultTimeout() methods.

Returns


TypeAsync

Added before v1.9 page.TypeAsync
Deprecated

In most cases, you should use Locator.FillAsync() instead. You only need to press keys one by one if there is special keyboard handling on the page - in this case use Locator.PressSequentiallyAsync().

Sends a keydown, keypress/input, and keyup event for each character in the text. page.type can be used to send fine-grained keyboard events. To fill values in form fields, use Page.FillAsync().

To press a special key, like Control or ArrowDown, use Keyboard.PressAsync().

Usage

Arguments

  • selector string#

    A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

  • text string#

    A text to type into a focused element.

  • options PageTypeOptions? (optional)

    • Delay [float]? (optional)#

      Time to wait between key presses in milliseconds. Defaults to 0.

    • NoWaitAfter bool? (optional)#

      Deprecated

      This option has no effect.

      This option has no effect.

    • Strict bool? (optional) Added in: v1.14#

      When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

    • Timeout [float]? (optional)#

      Maximum time in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout() or Page.SetDefaultTimeout() methods.

Returns


UncheckAsync

Added before v1.9 page.UncheckAsync
Discouraged

Use locator-based Locator.UncheckAsync() instead. Read more about locators.

This method unchecks an element matching selector by performing the following steps:

  1. Find an element matching selector. If there is none, wait until a matching element is attached to the DOM.
  2. Ensure that matched element is a checkbox or a radio input. If not, this method throws. If the element is already unchecked, this method returns immediately.
  3. Wait for actionability checks on the matched element, unless force option is set. If the element is detached during the checks, the whole action is retried.
  4. Scroll the element into view if needed.
  5. Use Page.Mouse to click in the center of the element.
  6. Ensure that the element is now unchecked. If not, this method throws.

When all steps combined have not finished during the specified timeout, this method throws a TimeoutError. Passing zero timeout disables this.

Usage

await Page.UncheckAsync(selector, options);

Arguments

  • selector string#

    A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

  • options PageUncheckOptions? (optional)

    • Force bool? (optional)#

      Whether to bypass the actionability checks. Defaults to false.

    • NoWaitAfter bool? (optional)#

      Deprecated

      This option has no effect.

      This option has no effect.

    • Position Position? (optional) Added in: v1.11#

      • X [float]

      • Y [float]

      A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of the element.

    • Strict bool? (optional) Added in: v1.14#

      When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

    • Timeout [float]? (optional)#

      Maximum time in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout() or Page.SetDefaultTimeout() methods.

    • Trial bool? (optional) Added in: v1.11#

      When set, this method only performs the actionability checks and skips the action. Defaults to false. Useful to wait until the element is ready for the action without performing it.

Returns


WaitForSelectorAsync

Added before v1.9 page.WaitForSelectorAsync
Discouraged

Use web assertions that assert visibility or a locator-based Locator.WaitForAsync() instead. Read more about locators.

Returns when element specified by selector satisfies state option. Returns null if waiting for hidden or detached.

note

Playwright automatically waits for element to be ready before performing an action. Using Locator objects and web-first assertions makes the code wait-for-selector-free.

Wait for the selector to satisfy state option (either appear/disappear from dom, or become visible/hidden). If at the moment of calling the method selector already satisfies the condition, the method will return immediately. If the selector doesn't satisfy the condition for the timeout milliseconds, the function will throw.

Usage

This method works across navigations:

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

class FrameExamples
{
public static async Task Images()
{
using var playwright = await Playwright.CreateAsync();
await using var browser = await playwright.Chromium.LaunchAsync();
var page = await browser.NewPageAsync();

foreach (var currentUrl in new[] { "https://www.google.com", "https://bbc.com" })
{
await page.GotoAsync(currentUrl);
var element = await page.WaitForSelectorAsync("img");
Console.WriteLine($"Loaded image: {await element.GetAttributeAsync("src")}");
}

await browser.CloseAsync();
}
}

Arguments

  • selector string#

    A selector to query for.

  • options PageWaitForSelectorOptions? (optional)

    • State enum WaitForSelectorState { Attached, Detached, Visible, Hidden }? (optional)#

      Defaults to 'visible'. Can be either:

      • 'attached' - wait for element to be present in DOM.
      • 'detached' - wait for element to not be present in DOM.
      • 'visible' - wait for element to have non-empty bounding box and no visibility:hidden. Note that element without any content or with display:none has an empty bounding box and is not considered visible.
      • 'hidden' - wait for element to be either detached from DOM, or have an empty bounding box or visibility:hidden. This is opposite to the 'visible' option.
    • Strict bool? (optional) Added in: v1.14#

      When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

    • Timeout [float]? (optional)#

      Maximum time in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout() or Page.SetDefaultTimeout() methods.

Returns


WaitForTimeoutAsync

Added before v1.9 page.WaitForTimeoutAsync
Discouraged

Never wait for timeout in production. Tests that wait for time are inherently flaky. Use Locator actions and web assertions that wait automatically.

Waits for the given timeout in milliseconds.

Note that page.waitForTimeout() should only be used for debugging. Tests using the timer in production are going to be flaky. Use signals such as network events, selectors becoming visible and others instead.

Usage

// Wait for 1 second
await page.WaitForTimeoutAsync(1000);

Arguments

  • timeout [float]#

    A timeout to wait for

Returns