File: class-page.md | Updated: 11/18/2025
On this 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
Added before v1.9 page.AddInitScriptAsync
Adds a script which would be evaluated in one of the following scenarios:
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.jsMath.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
Returns
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:
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 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
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)
Raw JavaScript content to be injected into frame.
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.
Script type. Use 'module' in order to load a JavaScript ES6 module. See script for more details.
URL of a script to be added.
Returns
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)
Returns
Added before v1.9 page.BringToFrontAsync
Brings page to front (activates tab).
Usage
await Page.BringToFrontAsync();
Returns
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
Added in: v1.56 page.ConsoleMessagesAsync
Returns up to (currently) 200 last console messages from this page. See Page.Console for more details.
Usage
await Page.ConsoleMessagesAsync();
Returns
Added before v1.9 page.ContentAsync
Gets the full HTML contents of the page, including the doctype.
Usage
await Page.ContentAsync();
Returns
Added before v1.9 page.Context
Get the browser context that the page belongs to.
Usage
Page.Context
Returns
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
A selector to search for an element to drag. If there are multiple elements satisfying the selector, the first will be used.
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)
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.
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
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");// → trueawait page.EvaluateAsync("() => matchMedia('print').matches");// → falseawait page.EmulateMediaAsync(new() { Media = Media.Print });await page.EvaluateAsync("() => matchMedia('screen').matches");// → falseawait page.EvaluateAsync("() => matchMedia('print').matches");// → trueawait page.EmulateMediaAsync(new() { Media = Media.Screen });await page.EvaluateAsync("() => matchMedia('screen').matches");// → trueawait page.EvaluateAsync("() => matchMedia('print').matches");// → false
await page.EmulateMediaAsync(new() { ColorScheme = ColorScheme.Dark });await page.EvaluateAsync("matchMedia('(prefers-color-scheme: dark)').matches");// → trueawait page.EvaluateAsync("matchMedia('(prefers-color-scheme: light)').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' and 'dark'. Passing 'Null' disables color scheme emulation. 'no-preference' is deprecated.
Contrast enum Contrast { NoPreference, More, Null }? (optional) Added in: v1.51#
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
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
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
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
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
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 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)
Returns
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 of the function on the window object
callback Action
<T, [TResult]>#
Callback function which will be called in Playwright's context.
Returns
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
Returns
Added in: v1.9 page.FrameByUrl
Returns frame with matching URL.
Usage
Page.FrameByUrl(url);
Arguments
url string
| Regex
| Func
<string
, bool>#
A glob pattern, regex pattern or predicate receiving frame's url as a URL
object.
Returns
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
Returns
Added before v1.9 page.Frames
An array of all frames attached to the page.
Usage
Page.Frames
Returns
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 to locate the element for.
options PageGetByAltTextOptions? (optional)
Returns
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 to locate the element for.
options PageGetByLabelOptions? (optional)
Returns
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 to locate the element for.
options PageGetByPlaceholderOptions? (optional)
Returns
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)
An attribute that is usually set by aria-checked or native <input type=checkbox> controls.
Learn more about aria-checked
.
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|NameRegex is matched exactly: case-sensitive and whole-string. Defaults to false. Ignored when Name|NameRegex is a regular expression. Note that exact match still trims whitespace.
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
.
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 .
An attribute that is usually set by aria-pressed.
Learn more about aria-pressed
.
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.
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.
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>spage.GetByText(new Regex("Hello"));// Matches second <div>page.GetByText(new Regex("^hello$", RegexOptions.IgnoreCase));
Arguments
Text to locate the element for.
options PageGetByTextOptions? (optional)
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">.
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 to locate the element for.
options PageGetByTitleOptions? (optional)
Returns
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
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
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:
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 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 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
Added before v1.9 page.IsClosed
Indicates that the page has been closed.
Usage
Page.IsClosed
Returns
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.
Usage
Page.Locator(selector, options);
Arguments
A selector to use when resolving DOM element.
options PageLocatorOptions? (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 FrameLocator s.
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 FrameLocator s.
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
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
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
Added in: v1.56 page.PageErrorsAsync
Returns up to (currently) 200 last page errors from this page. See Page.PageError for more details.
Usage
await Page.PageErrorsAsync();
Returns
Added in: v1.9 page.PauseAsync
Pauses script execution. Playwright will stop executing the script and wait for the user to either press the '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 option.
Usage
await Page.PauseAsync();
Returns
Added before v1.9 page.PdfAsync
Returns the PDF buffer.
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 typeawait 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 pixelspage.pdf({width: '100px'}) - prints with width set to 100 pixelspage.pdf({width: '10cm'}) - prints with width set to 10 centimeters.All possible units are:
px - pixelin - inchcm - centimetermm - millimeterThe Format options are:
Letter: 8.5in x 11inLegal: 8.5in x 14inTabloid: 11in x 17inLedger: 17in x 11inA0: 33.1in x 46.8inA1: 23.4in x 33.1inA2: 16.54in x 23.4inA3: 11.7in x 16.54inA4: 8.27in x 11.7inA5: 5.83in x 8.27inA6: 4.13in x 5.83innote
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 .
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 documentPaper height, accepts values labeled with units.
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.
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.
Paper width, accepts values labeled with units.
Returns
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
Added in: v1.44 page.RemoveLocatorHandlerAsync
Removes all locator handlers added by Page.AddLocatorHandlerAsync() for a specific locator.
Usage
await Page.RemoveLocatorHandlerAsync(locator);
Arguments
Locator passed to Page.AddLocatorHandlerAsync() .
Returns
Added in: v1.48 page.RequestGCAsync
Request the page to perform garbage collection. Note that there is no guarantee that all unreachable objects will be collected.
This is useful to help detect memory leaks. For example, if your page has a large object 'suspect' that might be leaked, you can check that it does not leak by using a WeakRef
.
// 1. In your page, save a WeakRef for the "suspect".await Page.EvaluateAsync("globalThis.suspectWeakRef = new WeakRef(suspect)");// 2. Request garbage collection.await Page.RequestGCAsync();// 3. Check that weak ref does not deref to the original object.Assert.True(await Page.EvaluateAsync("!globalThis.suspectWeakRef.deref()"));
Usage
await Page.RequestGCAsync();
Returns
Added in: v1.56 page.RequestsAsync
Returns up to (currently) 100 last network request from this page. See Page.Request for more details.
Returned requests should be accessed immediately, otherwise they might be collected to prevent unbounded memory growth as new requests come in. Once collected, retrieving most information about the request is impossible.
Note that requests reported through the Page.Request request are not collected, so there is a trade off between efficient memory usage with Page.RequestsAsync() and the amount of available information reported through Page.Request .
Usage
await Page.RequestsAsync();
Returns
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 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 that receives a URL
to match during routing. If BaseURL
is set in the context options and the provided URL is a string that does not start with *, it is resolved using the new URL()
constructor.
handler function to route the request.
options PageRouteOptions? (optional)
Returns
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 ServiceWorkers
to 'block'.
Usage
await Page.RouteFromHARAsync(har, options);
Arguments
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)#
Defaults to abort.
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
Added in: v1.48 page.RouteWebSocketAsync
This method allows to modify websocket connections that are made by the page.
Note that only WebSockets created after this method was called will be routed. It is recommended to call this method before navigating the page.
Usage
Below is an example of a simple mock that responds to a single message. See WebSocketRoute for more details and examples.
await page.RouteWebSocketAsync("/ws", ws => { ws.OnMessage(frame => { if (frame.Text == "request") ws.Send("response"); });});
Arguments
url string
| Regex
| Func
<string
, bool>#
Only WebSockets with the url matching this pattern will be routed. A string pattern can be relative to the BaseURL context option.
handler Action
<WebSocketRoute
>#
Handler function to route the WebSocket.
Returns
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
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
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
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
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
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
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
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
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
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
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 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
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
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)
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 BrowserContext.SetDefaultTimeout()
or Page.SetDefaultTimeout()
methods.
Returns
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)
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 BrowserContext.SetDefaultTimeout()
or Page.SetDefaultTimeout()
methods.
Returns
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
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
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
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
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:
transitionend event.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.
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. The mask is also applied to invisible elements, see Matching only visible elements
to disable that.
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.
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.
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
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 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
Added before v1.9 page.SetDefaultNavigationTimeout
This setting will change the default maximum navigation time for the following methods and related shortcuts:
note
Page.SetDefaultNavigationTimeout() takes priority over Page.SetDefaultTimeout() , BrowserContext.SetDefaultTimeout() and BrowserContext.SetDefaultNavigationTimeout() .
Usage
Page.SetDefaultNavigationTimeout(timeout);
Arguments
timeout [float]#
Maximum navigation time in milliseconds
Added before v1.9 page.SetDefaultTimeout
This setting will change the default maximum time for all the methods accepting timeout option.
note
Page.SetDefaultNavigationTimeout() takes priority over Page.SetDefaultTimeout() .
Usage
Page.SetDefaultTimeout(timeout);
Arguments
timeout [float]#
Maximum time in milliseconds. Pass 0 to disable timeout.
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
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
Returns
Added before v1.9 page.TitleAsync
Returns the page's title.
Usage
await Page.TitleAsync();
Returns
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
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 caughtReturns
Added before v1.9 page.Url
Usage
Page.Url
Returns
Added before v1.9 page.Video
Video object associated with this page.
Usage
Page.Video
Returns
Added before v1.9 page.ViewportSize
Usage
Page.ViewportSize
Returns
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
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
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)
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.
Returns
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 navigationawait 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
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
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
Added in: v1.45 page.Clock
Playwright has ability to mock clock and passage of time.
Usage
Page.Clock
Type
Added before v1.9 page.Keyboard
Usage
Page.Keyboard
Type
Added before v1.9 page.Mouse
Usage
Page.Mouse
Type
Added before v1.9 page.Touchscreen
Usage
Page.Touchscreen
Type
Events
Added before v1.9 page.event Close
Emitted when the page closes.
Usage
Page.Close += async (_, page) => {};
Event data
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
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
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
Added in: v1.9 page.event DOMContentLoaded
Emitted when the JavaScript DOMContentLoaded
event is dispatched.
Usage
Page.DOMContentLoaded += async (_, page) => {};
Event data
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
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
Added in: v1.9 page.event FrameAttached
Emitted when a frame is attached.
Usage
Page.FrameAttached += async (_, frame) => {};
Event data
Added in: v1.9 page.event FrameDetached
Emitted when a frame is detached.
Usage
Page.FrameDetached += async (_, frame) => {};
Event data
Added in: v1.9 page.event FrameNavigated
Emitted when a frame is navigated to a new url.
Usage
Page.FrameNavigated += async (_, frame) => {};
Event data
Added before v1.9 page.event Load
Emitted when the JavaScript load
event is dispatched.
Usage
Page.Load += async (_, page) => {};
Event data
Added in: v1.9 page.event PageError
Emitted when an uncaught exception happens within the page.
// Log all uncaught errors to the terminalpage.PageError += (_, exception) =>{ Console.WriteLine("Uncaught exception: " + exception);};
Usage
Page.PageError += async (_, value) => {};
Event data
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
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
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
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
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
Added in: v1.9 page.event WebSocket
Emitted when WebSocket request is sent.
Usage
Page.WebSocket += async (_, webSocket) => {};
Event data
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
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
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:
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
A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
options PageCheckOptions? (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
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:
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
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.
defaults to 1. See UIEvent.detail .
Delay [float]? (optional)#
Time to wait between mousedown and mouseup in milliseconds. Defaults to 0.
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. Note that keyboard modifiers will be pressed regardless of trial to allow testing elements which are only visible when those keys are pressed.
Returns
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:
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
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.
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. Note that keyboard modifiers will be pressed regardless of trial to allow testing elements which are only visible when those keys are pressed.
Returns
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
A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
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
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
A selector to query for.
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)
Returns
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
A selector to query for.
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
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
A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
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
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
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
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
A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
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
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:
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
A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
options PageHoverOptions? (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. Note that keyboard modifiers will be pressed regardless of trial to allow testing elements which are only visible when those keys are pressed.
Returns
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
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
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
A selector to query for.
options PageQuerySelectorOptions? (optional)
Returns
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
Returns
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
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
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 labelawait page.SelectOptionAsync("select#colors", new[] { "blue" });// single selection matching both the value and the labelawait page.SelectOptionAsync("select#colors", new[] { new SelectOptionValue() { Label = "blue" } });// multipleawait page.SelectOptionAsync("select#colors", new[] { "red", "green", "blue" });
Arguments
A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
values string
| ElementHandle
| IEnumerable
| SelectOption | IEnumerable
| IEnumerable
?#
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
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:
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
A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
Whether to check or uncheck the checkbox.
options PageSetCheckedOptions? (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.
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.
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
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
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
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:
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
A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
options PageTapOptions? (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. Note that keyboard modifiers will be pressed regardless of trial to allow testing elements which are only visible when those keys are pressed.
Returns
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
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
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
A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
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
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:
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
A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
options PageUncheckOptions? (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
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
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
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 secondawait page.WaitForTimeoutAsync(1000);
Arguments
timeout [float]#
A timeout to wait for
Returns