Page
Page provides methods to interact with a single tab in a Browser, or an extension background page in Chromium. One Browser instance might have multiple Page instances.
This example creates a page, navigates it to a URL, and then saves a screenshot:
using Microsoft.Playwright;
using System.Threading.Tasks;
class PageExamples
{
public static async Task Run()
{
using var playwright = await Playwright.CreateAsync();
await using var browser = await playwright.Webkit.LaunchAsync();
var page = await browser.NewPageAsync();
await page.GotoAsync("https://www.theverge.com");
await page.ScreenshotAsync(new() { Path = "theverge.png" });
}
}
The Page class emits various events (described below) which can be handled using any of Node's native EventEmitter
methods, such as on
, once
or removeListener
.
This example logs a message for a single page load
event:
page.Load += (_, _) => Console.WriteLine("Page loaded!");
To unsubscribe from events use the removeListener
method:
void PageLoadHandler(object _, IPage p) {
Console.WriteLine("Page loaded!");
};
page.Load += PageLoadHandler;
// Do some work...
page.Load -= PageLoadHandler;
Methods
AddInitScriptAsync
Added before v1.9Adds a script which would be evaluated in one of the following scenarios:
- Whenever the page is navigated.
- Whenever the child frame is attached or navigated. In this case, the script is evaluated in the context of the newly attached frame.
The script is evaluated after the document was created but before any of its scripts were run. This is useful to amend the JavaScript environment, e.g. to seed Math.random
.
Usage
An example of overriding Math.random
before the page loads:
// preload.js
Math.random = () => 42;
await Page.AddInitScriptAsync(scriptPath: "./preload.js");
The order of evaluation of multiple scripts installed via BrowserContext.AddInitScriptAsync() and Page.AddInitScriptAsync() is not defined.
Arguments
Returns
AddLocatorHandlerAsync
Added in: v1.42When testing a web page, sometimes unexpected overlays like a "Sign up" dialog appear and block actions you want to automate, e.g. clicking a button. These overlays don't always show up in the same way or at the same time, making them tricky to handle in automated tests.
This method lets you set up a special function, called a handler, that activates when it detects that overlay is visible. The handler's job is to remove the overlay, allowing your test to continue as if the overlay wasn't there.
Things to keep in mind:
- When an overlay is shown predictably, we recommend explicitly waiting for it in your test and dismissing it as a part of your normal test flow, instead of using Page.AddLocatorHandlerAsync().
- Playwright checks for the overlay every time before executing or retrying an action that requires an actionability check, or before performing an auto-waiting assertion check. When overlay is visible, Playwright calls the handler first, and then proceeds with the action/assertion. Note that the handler is only called when you perform an action/assertion - if the overlay becomes visible but you don't perform any actions, the handler will not be triggered.
- After executing the handler, Playwright will ensure that overlay that triggered the handler is not visible anymore. You can opt-out of this behavior with NoWaitAfter.
- The execution time of the handler counts towards the timeout of the action/assertion that executed the handler. If your handler takes too long, it might cause timeouts.
- You can register multiple handlers. However, only a single handler will be running at a time. Make sure the actions within a handler don't depend on another handler.
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.
-
Function that should be run once locator appears. This function should get rid of the element that blocks actions like click.
-
options
PageAddLocatorHandlerOptions?
(optional)-
NoWaitAfter
bool? (optional) Added in: v1.44#By default, after calling the handler Playwright will wait until the overlay becomes hidden, and only then Playwright will continue with the action/assertion that triggered the handler. This option allows to opt-out of this behavior, so that overlay can stay visible after the handler has run.
-
Times
int? (optional) Added in: v1.44#Specifies the maximum number of times this handler should be called. Unlimited by default.
-
Returns
AddScriptTagAsync
Added before v1.9Adds 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
AddStyleTagAsync
Added before v1.9Adds 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
BringToFrontAsync
Added before v1.9Brings page to front (activates tab).
Usage
await Page.BringToFrontAsync();
Returns
CloseAsync
Added before v1.9If 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.
if RunBeforeUnload is passed as true, a beforeunload
dialog might be summoned and should be handled manually via Page.Dialog event.
Usage
await Page.CloseAsync(options);
Arguments
options
PageCloseOptions?
(optional)-
Reason
string? (optional) Added in: v1.40#The reason to be reported to the operations interrupted by the page closure.
-
RunBeforeUnload
bool? (optional)#Defaults to
false
. Whether to run the before unload page handlers.
-
Returns
ContentAsync
Added before v1.9Gets the full HTML contents of the page, including the doctype.
Usage
await Page.ContentAsync();
Returns
Context
Added before v1.9Get the browser context that the page belongs to.
Usage
Page.Context
Returns
DragAndDropAsync
Added in: v1.13This 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
. -
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). Pass0
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
EmulateMediaAsync
Added before v1.9This method changes the CSS media type
through the media
argument, and/or the 'prefers-colors-scheme'
media feature, using the colorScheme
argument.
Usage
await page.EvaluateAsync("() => matchMedia('screen').matches");
// → true
await page.EvaluateAsync("() => matchMedia('print').matches");
// → false
await page.EmulateMediaAsync(new() { Media = Media.Print });
await page.EvaluateAsync("() => matchMedia('screen').matches");
// → false
await page.EvaluateAsync("() => matchMedia('print').matches");
// → true
await page.EmulateMediaAsync(new() { Media = Media.Screen });
await page.EvaluateAsync("() => matchMedia('screen').matches");
// → true
await page.EvaluateAsync("() => matchMedia('print').matches");
// → false
await page.EmulateMediaAsync(new() { ColorScheme = ColorScheme.Dark });
await page.EvaluateAsync("matchMedia('(prefers-color-scheme: dark)').matches");
// → true
await page.EvaluateAsync("matchMedia('(prefers-color-scheme: light)').matches");
// → false
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. -
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'
. Passingnull
disables reduced motion emulation.
-
Returns
EvaluateAsync
Added before v1.9Returns 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
- [object]#
EvaluateHandleAsync
Added before v1.9Returns 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
ExposeBindingAsync
Added before v1.9The 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.
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
ExposeFunctionAsync
Added before v1.9The 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.
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
Frame
Added before v1.9Returns 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
FrameByUrl
Added in: v1.9Returns 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
FrameLocator
Added in: v1.17When 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
Frames
Added before v1.9An array of all frames attached to the page.
Usage
Page.Frames
Returns
GetByAltText
Added in: v1.27Allows 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
GetByLabel
Added in: v1.27Allows 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
GetByPlaceholder
Added in: v1.27Allows 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
GetByRole
Added in: v1.27Allows 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
ordisabled
.noteUnlike most other attributes,
disabled
is inherited through the DOM hierarchy. Learn more aboutaria-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.
GetByTestId
Added in: v1.27Locate element by the test id.
Usage
Consider the following DOM structure.
<button data-testid="directions">Itinéraire</button>
You can locate the element by it's test id:
await page.GetByTestId("directions").ClickAsync();
Arguments
Returns
Details
By default, the data-testid
attribute is used as a test id. Use Selectors.SetTestIdAttribute() to configure a different test id attribute if necessary.
GetByText
Added in: v1.27Allows locating elements that contain given text.
See also Locator.Filter() that allows to match by another criteria, like an accessible role, and then filter by the text content.
Usage
Consider the following DOM structure:
<div>Hello <span>world</span></div>
<div>Hello</div>
You can locate by text substring, exact string, or a regular expression:
// Matches <span>
page.GetByText("world");
// Matches first <div>
page.GetByText("Hello world");
// Matches second <div>
page.GetByText("Hello", new() { Exact = true });
// Matches both <div>s
page.GetByText(new Regex("Hello"));
// Matches second <div>
page.GetByText(new Regex("^hello$", RegexOptions.IgnoreCase));
Arguments
-
Text 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">
.
GetByTitle
Added in: v1.27Allows 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
GoBackAsync
Added before v1.9Returns 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 theDOMContentLoaded
event is fired.'load'
- consider operation to be finished when theload
event is fired.'networkidle'
- DISCOURAGED consider operation to be finished when there are no network connections for at least500
ms. Don't use this method for testing, rely on web assertions to assess readiness instead.'commit'
- consider operation to be finished when network response is received and the document started loading.
-
Returns
GoForwardAsync
Added before v1.9Returns 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 theDOMContentLoaded
event is fired.'load'
- consider operation to be finished when theload
event is fired.'networkidle'
- DISCOURAGED consider operation to be finished when there are no network connections for at least500
ms. Don't use this method for testing, rely on web assertions to assess readiness instead.'commit'
- consider operation to be finished when network response is received and the document started loading.
-
Returns
GotoAsync
Added before v1.9Returns the main resource response. In case of multiple redirects, the navigation will resolve with the first non-redirect response.
The method will throw an error if:
- there's an SSL error (e.g. in case of self-signed certificates).
- target URL is invalid.
- the Timeout is exceeded during navigation.
- the remote server does not respond or is unreachable.
- the main resource failed to load.
The method will not throw an error when any valid HTTP status code is returned by the remote server, including 404 "Not Found" and 500 "Internal Server Error". The status code for such responses can be retrieved by calling Response.Status.
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
.
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 thenew 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 theDOMContentLoaded
event is fired.'load'
- consider operation to be finished when theload
event is fired.'networkidle'
- DISCOURAGED consider operation to be finished when there are no network connections for at least500
ms. Don't use this method for testing, rely on web assertions to assess readiness instead.'commit'
- consider operation to be finished when network response is received and the document started loading.
-
Returns
IsClosed
Added before v1.9Indicates that the page has been closed.
Usage
Page.IsClosed
Returns
Locator
Added in: v1.14The 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 hastext=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 hasdiv
in<article><content><div>Playwright</div></content></article>
. However, looking forcontent
that hasarticle div
will fail, because the inner locator must be relative and should not use any elements outside thecontent
.Note that outer and inner locators must belong to the same frame. Inner locator must not contain FrameLocators.
-
HasNot
Locator? (optional) Added in: v1.33#Matches elements that do not contain an element that matches an inner locator. Inner locator is queried against the outer one. For example,
article
that does not havediv
matches<article><span>Playwright</span></article>
.Note that outer and inner locators must belong to the same frame. Inner locator must not contain FrameLocators.
-
HasNotText|HasNotTextRegex
string? | Regex? (optional) Added in: v1.33#Matches elements that do not contain specified text somewhere inside, possibly in a child or a descendant element. When passed a string, matching is case-insensitive and searches for a substring.
-
HasText|HasTextRegex
string? | Regex? (optional)#Matches elements containing specified text somewhere inside, possibly in a child or a descendant element. When passed a string, matching is case-insensitive and searches for a substring. For example,
"Playwright"
matches<article><div>Playwright</div></article>
.
-
Returns
MainFrame
Added before v1.9The page's main frame. Page is guaranteed to have a main frame which persists during navigations.
Usage
Page.MainFrame
Returns
OpenerAsync
Added before v1.9Returns the opener for popup pages and null
for others. If the opener has been closed already the returns null
.
Usage
await Page.OpenerAsync();
Returns
PauseAsync
Added in: v1.9Pauses script execution. Playwright will stop executing the script and wait for the user to either press 'Resume' button in the page overlay or to call playwright.resume()
in the DevTools console.
User can inspect selectors or perform manual steps while paused. Resume will continue running the original script from the place it was paused.
This method requires Playwright to be started in a headed mode, with a falsy Headless option.
Usage
await Page.PauseAsync();
Returns
PdfAsync
Added before v1.9Returns the PDF buffer.
Generating a pdf is currently only supported in Chromium headless.
page.pdf()
generates a pdf of the page with print
css media. To generate a pdf with screen
media, call Page.EmulateMediaAsync() before calling page.pdf()
:
By default, page.pdf()
generates a pdf with modified colors for printing. Use the -webkit-print-color-adjust
property to force rendering of exact colors.
Usage
// Generates a PDF with 'screen' media type
await page.EmulateMediaAsync(new() { Media = Media.Screen });
await page.PdfAsync(new() { Path = "page.pdf" });
The Width, Height, and Margin options accept values labeled with units. Unlabeled values are treated as pixels.
A few examples:
page.pdf({width: 100})
- prints with width set to 100 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
- millimeter
The 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.83in
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 document
-
Paper 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 tofalse
, 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
ReloadAsync
Added before v1.9This 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 theDOMContentLoaded
event is fired.'load'
- consider operation to be finished when theload
event is fired.'networkidle'
- DISCOURAGED consider operation to be finished when there are no network connections for at least500
ms. Don't use this method for testing, rely on web assertions to assess readiness instead.'commit'
- consider operation to be finished when network response is received and the document started loading.
-
Returns
RemoveLocatorHandlerAsync
Added in: v1.44Removes all locator handlers added by Page.AddLocatorHandlerAsync() for a specific locator.
Usage
await Page.RemoveLocatorHandlerAsync(locator);
Arguments
-
Locator passed to Page.AddLocatorHandlerAsync().
Returns
RequestGCAsync
Added in: v1.48Request 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
RouteAsync
Added before v1.9Routing 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.
The handler will only be called for the first url if the response is a redirect.
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'
.
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().
Enabling routing disables http cache.
Arguments
-
url
string | Regex | Func<string, bool>#A glob pattern, regex pattern or predicate receiving URL to match while routing. When a BaseURL via the context options was provided and the passed URL is a path, it gets merged via the
new URL()
constructor. -
handler function to route the request.
-
options
PageRouteOptions?
(optional)
Returns
RouteFromHARAsync
Added in: v1.23If 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)#- If set to 'abort' any request not found in the HAR file will be aborted.
- If set to 'fallback' missing requests will be sent to the network.
Defaults to abort.
-
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. Ifembed
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 tominimal
. -
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
RouteWebSocketAsync
Added in: v1.48This method allows to modify websocket connections that are made by the page.
Note that only WebSocket
s 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
RunAndWaitForConsoleMessageAsync
Added in: v1.9Performs 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). Pass0
to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout().
-
Returns
WaitForConsoleMessageAsync
Added in: v1.9Performs 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). Pass0
to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout().
-
Returns
RunAndWaitForDownloadAsync
Added in: v1.9Performs 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). Pass0
to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout().
-
Returns
WaitForDownloadAsync
Added in: v1.9Performs 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). Pass0
to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout().
-
Returns
RunAndWaitForFileChooserAsync
Added in: v1.9Performs 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). Pass0
to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout().
-
Returns
WaitForFileChooserAsync
Added in: v1.9Performs 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). Pass0
to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout().
-
Returns
RunAndWaitForPopupAsync
Added in: v1.9Performs 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). Pass0
to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout().
-
Returns
WaitForPopupAsync
Added in: v1.9Performs 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). Pass0
to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout().
-
Returns
RunAndWaitForRequestAsync
Added before v1.9Waits for the matching request and returns it. See waiting for event for more details about events.
Usage
// Waits for the next request with the specified url.
await page.RunAndWaitForRequestAsync(async () =>
{
await page.GetByText("trigger request").ClickAsync();
}, "http://example.com/resource");
// Alternative way with a predicate.
await page.RunAndWaitForRequestAsync(async () =>
{
await page.GetByText("trigger request").ClickAsync();
}, request => request.Url == "https://example.com" && request.Method == "GET");
Arguments
-
action
Func<Task> Added in: v1.12#Action that triggers the event.
-
urlOrPredicate
string | Regex | Func<Request, bool>#Request URL string, regex or predicate receiving Request object. When a BaseURL via the context options was provided and the passed URL is a path, it gets merged via the
new URL()
constructor. -
options
PageRunAndWaitForRequestOptions?
(optional)-
Timeout
[float]? (optional)#Maximum wait time in milliseconds, defaults to 30 seconds, pass
0
to disable the timeout. The default value can be changed by using the Page.SetDefaultTimeout() method.
-
Returns
WaitForRequestAsync
Added before v1.9Waits for the matching request and returns it. See waiting for event for more details about events.
Usage
// Waits for the next request with the specified url.
await page.RunAndWaitForRequestAsync(async () =>
{
await page.GetByText("trigger request").ClickAsync();
}, "http://example.com/resource");
// Alternative way with a predicate.
await page.RunAndWaitForRequestAsync(async () =>
{
await page.GetByText("trigger request").ClickAsync();
}, request => request.Url == "https://example.com" && request.Method == "GET");
Arguments
-
urlOrPredicate
string | Regex | Func<Request, bool>#Request URL string, regex or predicate receiving Request object. When a BaseURL via the context options was provided and the passed URL is a path, it gets merged via the
new URL()
constructor. -
options
PageRunAndWaitForRequestOptions?
(optional)-
Timeout
[float]? (optional)#Maximum wait time in milliseconds, defaults to 30 seconds, pass
0
to disable the timeout. The default value can be changed by using the Page.SetDefaultTimeout() method.
-
Returns
RunAndWaitForRequestFinishedAsync
Added in: v1.12Performs 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). Pass0
to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout().
-
Returns
WaitForRequestFinishedAsync
Added in: v1.12Performs 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). Pass0
to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout().
-
Returns
RunAndWaitForResponseAsync
Added before v1.9Returns 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
WaitForResponseAsync
Added before v1.9Returns 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
RunAndWaitForWebSocketAsync
Added in: v1.9Performs 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). Pass0
to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout().
-
Returns
WaitForWebSocketAsync
Added in: v1.9Performs 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). Pass0
to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout().
-
Returns
RunAndWaitForWorkerAsync
Added in: v1.9Performs 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). Pass0
to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout().
-
Returns
WaitForWorkerAsync
Added in: v1.9Performs 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). Pass0
to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout().
-
Returns
ScreenshotAsync
Added before v1.9Returns the buffer with the captured screenshot.
Usage
await Page.ScreenshotAsync(options);
Arguments
options
PageScreenshotOptions?
(optional)-
Animations
enum ScreenshotAnimations { Disabled, Allow }?
(optional)#When set to
"disabled"
, stops CSS animations, CSS transitions and Web Animations. Animations get different treatment depending on their duration:- finite animations are fast-forwarded to completion, so they'll fire
transitionend
event. - infinite animations are canceled to initial state, and then played over after the screenshot.
Defaults to
"allow"
that leaves animations untouched. - finite animations are fast-forwarded to completion, so they'll fire
-
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. -
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 tofalse
. -
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). Pass0
to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout() or Page.SetDefaultTimeout() methods. -
Type
enum ScreenshotType { Png, Jpeg }?
(optional)#Specify screenshot type, defaults to
png
.
-
Returns
SetContentAsync
Added before v1.9This 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 theDOMContentLoaded
event is fired.'load'
- consider operation to be finished when theload
event is fired.'networkidle'
- DISCOURAGED consider operation to be finished when there are no network connections for at least500
ms. Don't use this method for testing, rely on web assertions to assess readiness instead.'commit'
- consider operation to be finished when network response is received and the document started loading.
-
Returns
SetDefaultNavigationTimeout
Added before v1.9This setting will change the default maximum navigation time for the following methods and related shortcuts:
- Page.GoBackAsync()
- Page.GoForwardAsync()
- Page.GotoAsync()
- Page.ReloadAsync()
- Page.SetContentAsync()
- Page.RunAndWaitForNavigationAsync()
- Page.WaitForURLAsync()
Usage
Page.SetDefaultNavigationTimeout(timeout);
Arguments
-
timeout
[float]#Maximum navigation time in milliseconds
SetDefaultTimeout
Added before v1.9This setting will change the default maximum time for all the methods accepting timeout option.
Page.SetDefaultNavigationTimeout() takes priority over Page.SetDefaultTimeout().
Usage
Page.SetDefaultTimeout(timeout);
Arguments
-
timeout
[float]#Maximum time in milliseconds
SetExtraHTTPHeadersAsync
Added before v1.9The extra HTTP headers will be sent with every request the page initiates.
Page.SetExtraHTTPHeadersAsync() does not guarantee the order of headers in the outgoing requests.
Usage
await Page.SetExtraHTTPHeadersAsync(headers);
Arguments
-
headers
IDictionary<string, string>#An object containing additional HTTP headers to be sent with every request. All header values must be strings.
Returns
SetViewportSizeAsync
Added before v1.9In 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
TitleAsync
Added before v1.9Returns the page's title.
Usage
await Page.TitleAsync();
Returns
UnrouteAsync
Added before v1.9Removes a route created with Page.RouteAsync(). When handler is not specified, removes all routes for the url.
Usage
await Page.UnrouteAsync(url, handler);
Arguments
-
url
string | Regex | Func<string, bool>#A glob pattern, regex pattern or predicate receiving URL to match while routing.
-
handler
Action<Route?> (optional)#Optional handler function to route the request.
Returns
UnrouteAllAsync
Added in: v1.41Removes all routes created with Page.RouteAsync() and Page.RouteFromHARAsync().
Usage
await Page.UnrouteAllAsync(options);
Arguments
options
PageUnrouteAllOptions?
(optional)-
Behavior
enum UnrouteBehavior { Wait, IgnoreErrors, Default }?
(optional)#Specifies whether to wait for already running handlers and what to do if they throw errors:
'default'
- do not wait for current handler calls (if any) to finish, if unrouted handler throws, it may result in unhandled error'wait'
- wait for current handler calls (if any) to finish'ignoreErrors'
- do not wait for current handler calls (if any) to finish, all errors thrown by the handlers after unrouting are silently caught
-
Returns
Url
Added before v1.9Usage
Page.Url
Returns
Video
Added before v1.9Video object associated with this page.
Usage
Page.Video
Returns
ViewportSize
Added before v1.9Usage
Page.ViewportSize
Returns
WaitForFunctionAsync
Added before v1.9Returns 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). Pass0
to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout() or Page.SetDefaultTimeout() methods.
-
Returns
WaitForLoadStateAsync
Added before v1.9Returns 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.
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 theload
event to be fired.'domcontentloaded'
- wait for theDOMContentLoaded
event to be fired.'networkidle'
- DISCOURAGED wait until there are no network connections for at least500
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
WaitForURLAsync
Added in: v1.11Waits for the main frame to navigate to the given URL.
Usage
await page.ClickAsync("a.delayed-navigation"); // clicking the link will indirectly cause a navigation
await page.WaitForURLAsync("**/target.html");
Arguments
-
url
string | Regex | Func<string, bool>#A glob pattern, regex pattern or predicate receiving URL to match while waiting for the navigation. Note that if the parameter is a string without wildcard characters, the method will wait for navigation to URL that is exactly equal to the string.
-
options
PageWaitForURLOptions?
(optional)-
Timeout
[float]? (optional)#Maximum operation time in milliseconds, defaults to 30 seconds, pass
0
to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultNavigationTimeout(), BrowserContext.SetDefaultTimeout(), Page.SetDefaultNavigationTimeout() or Page.SetDefaultTimeout() methods. -
WaitUntil
enum WaitUntilState { Load, DOMContentLoaded, NetworkIdle, Commit }?
(optional)#When to consider operation succeeded, defaults to
load
. Events can be either:'domcontentloaded'
- consider operation to be finished when theDOMContentLoaded
event is fired.'load'
- consider operation to be finished when theload
event is fired.'networkidle'
- DISCOURAGED consider operation to be finished when there are no network connections for at least500
ms. Don't use this method for testing, rely on web assertions to assess readiness instead.'commit'
- consider operation to be finished when network response is received and the document started loading.
-
Returns
Workers
Added before v1.9This method returns all of the dedicated WebWorkers associated with the page.
This does not contain ServiceWorkers
Usage
Page.Workers
Returns
Properties
APIRequest
Added in: v1.16API testing helper associated with this page. This method returns the same instance as BrowserContext.APIRequest on the page's context. See BrowserContext.APIRequest for more details.
Usage
Page.APIRequest
Type
Clock
Added in: v1.45Playwright has ability to mock clock and passage of time.
Usage
Page.Clock
Type
Keyboard
Added before v1.9Usage
Page.Keyboard
Type
Mouse
Added before v1.9Usage
Page.Mouse
Type
Touchscreen
Added before v1.9Usage
Page.Touchscreen
Type
Events
event Close
Added before v1.9Emitted when the page closes.
Usage
Page.Close += async (_, page) => {};
Event data
event Console
Added before v1.9Emitted when JavaScript within the page calls one of console API methods, e.g. console.log
or console.dir
.
The arguments passed into console.log
are available on the ConsoleMessage event handler argument.
Usage
page.Console += async (_, msg) =>
{
foreach (var arg in msg.Args)
Console.WriteLine(await arg.JsonValueAsync<object>());
};
await page.EvaluateAsync("console.log('hello', 5, { foo: 'bar' })");
Event data
event Crash
Added before v1.9Emitted when the page crashes. Browser pages might crash if they try to allocate too much memory. When the page crashes, ongoing and subsequent operations will throw.
The most common way to deal with crashes is to catch an exception:
try {
// Crash might happen during a click.
await page.ClickAsync("button");
// Or while waiting for an event.
await page.WaitForPopup();
} catch (PlaywrightException e) {
// When the page crashes, exception message contains "crash".
}
Usage
Page.Crash += async (_, page) => {};
Event data
event Dialog
Added before v1.9Emitted 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);
};
When no Page.Dialog or BrowserContext.Dialog listeners are present, all dialogs are automatically dismissed.
Event data
event DOMContentLoaded
Added in: v1.9Emitted when the JavaScript DOMContentLoaded
event is dispatched.
Usage
Page.DOMContentLoaded += async (_, page) => {};
Event data
event Download
Added before v1.9Emitted when attachment download started. User can access basic file operations on downloaded content via the passed Download instance.
Usage
Page.Download += async (_, download) => {};
Event data
event FileChooser
Added in: v1.9Emitted when a file chooser is supposed to appear, such as after clicking the <input type=file>
. Playwright can respond to it via setting the input files using FileChooser.SetFilesAsync() that can be uploaded after that.
page.FileChooser += (_, fileChooser) =>
{
fileChooser.SetFilesAsync(@"C:\temp\myfile.pdf");
};
Usage
Page.FileChooser += async (_, fileChooser) => {};
Event data
event FrameAttached
Added in: v1.9Emitted when a frame is attached.
Usage
Page.FrameAttached += async (_, frame) => {};
Event data
event FrameDetached
Added in: v1.9Emitted when a frame is detached.
Usage
Page.FrameDetached += async (_, frame) => {};
Event data
event FrameNavigated
Added in: v1.9Emitted when a frame is navigated to a new url.
Usage
Page.FrameNavigated += async (_, frame) => {};
Event data
event Load
Added before v1.9Emitted when the JavaScript load
event is dispatched.
Usage
Page.Load += async (_, page) => {};
Event data
event PageError
Added in: v1.9Emitted when an uncaught exception happens within the page.
// Log all uncaught errors to the terminal
page.PageError += (_, exception) =>
{
Console.WriteLine("Uncaught exception: " + exception);
};
Usage
Page.PageError += async (_, value) => {};
Event data
event Popup
Added before v1.9Emitted 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"));
Use Page.WaitForLoadStateAsync() to wait until the page gets to a particular state (you should not need it in most cases).
Usage
Page.Popup += async (_, page) => {};
Event data
event Request
Added before v1.9Emitted when a page issues a request. The request object is read-only. In order to intercept and mutate requests, see Page.RouteAsync() or BrowserContext.RouteAsync().
Usage
Page.Request += async (_, request) => {};
Event data
event RequestFailed
Added in: v1.9Emitted when a request fails, for example by timing out.
HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request will complete with Page.RequestFinished event and not with Page.RequestFailed. A request will only be considered failed when the client cannot get an HTTP response from the server, e.g. due to network error net::ERR_FAILED.
Usage
Page.RequestFailed += async (_, request) => {};
Event data
event RequestFinished
Added in: v1.9Emitted when a request finishes successfully after downloading the response body. For a successful response, the sequence of events is request
, response
and requestfinished
.
Usage
Page.RequestFinished += async (_, request) => {};
Event data
event Response
Added before v1.9Emitted when response status and headers are received for a request. For a successful response, the sequence of events is request
, response
and requestfinished
.
Usage
Page.Response += async (_, response) => {};
Event data
event WebSocket
Added in: v1.9Emitted when WebSocket request is sent.
Usage
Page.WebSocket += async (_, webSocket) => {};
Event data
event Worker
Added before v1.9Emitted when a dedicated WebWorker is spawned by the page.
Usage
Page.Worker += async (_, worker) => {};
Event data
Deprecated
Accessibility
Added before v1.9Usage
Page.Accessibility
Type
CheckAsync
Added before v1.9Use locator-based Locator.CheckAsync() instead. Read more about locators.
This method checks an element matching selector by performing the following steps:
- Find an element matching selector. If there is none, wait until a matching element is attached to the DOM.
- Ensure that matched element is a checkbox or a radio input. If not, this method throws. If the element is already checked, this method returns immediately.
- Wait for actionability checks on the matched element, unless Force option is set. If the element is detached during the checks, the whole action is retried.
- Scroll the element into view if needed.
- Use Page.Mouse to click in the center of the element.
- Ensure that the element is now checked. If not, this method throws.
When all steps combined have not finished during the specified Timeout, this method throws a TimeoutError. Passing zero timeout disables this.
Usage
await Page.CheckAsync(selector, options);
Arguments
-
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
. -
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). Pass0
to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout() or Page.SetDefaultTimeout() methods. -
Trial
bool? (optional) Added in: v1.11#When set, this method only performs the actionability checks and skips the action. Defaults to
false
. Useful to wait until the element is ready for the action without performing it.
-
Returns
ClickAsync
Added before v1.9Use locator-based Locator.ClickAsync() instead. Read more about locators.
This method clicks an element matching selector by performing the following steps:
- Find an element matching selector. If there is none, wait until a matching element is attached to the DOM.
- Wait for actionability checks on the matched element, unless Force option is set. If the element is detached during the checks, the whole action is retried.
- Scroll the element into view if needed.
- Use Page.Mouse to click in the center of the element, or the specified Position.
- Wait for initiated navigations to either succeed or fail, unless NoWaitAfter option is set.
When all steps combined have not finished during the specified Timeout, this method throws a TimeoutError. Passing zero timeout disables this.
Usage
await Page.ClickAsync(selector, options);
Arguments
-
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
andmouseup
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.
-
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). Pass0
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 keyboardmodifiers
will be pressed regardless oftrial
to allow testing elements which are only visible when those keys are pressed.
-
Returns
DblClickAsync
Added before v1.9Use locator-based Locator.DblClickAsync() instead. Read more about locators.
This method double clicks an element matching selector by performing the following steps:
- Find an element matching selector. If there is none, wait until a matching element is attached to the DOM.
- Wait for actionability checks on the matched element, unless Force option is set. If the element is detached during the checks, the whole action is retried.
- Scroll the element into view if needed.
- Use Page.Mouse to double click in the center of the element, or the specified Position.
When all steps combined have not finished during the specified Timeout, this method throws a TimeoutError. Passing zero timeout disables this.
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
andmouseup
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.
-
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). Pass0
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 keyboardmodifiers
will be pressed regardless oftrial
to allow testing elements which are only visible when those keys are pressed.
-
Returns
DispatchEventAsync
Added before v1.9Use 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:
- DeviceMotionEvent
- DeviceOrientationEvent
- DragEvent
- Event
- FocusEvent
- KeyboardEvent
- MouseEvent
- PointerEvent
- TouchEvent
- WheelEvent
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). Pass0
to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout() or Page.SetDefaultTimeout() methods.
-
Returns
EvalOnSelectorAsync
Added in: v1.9This 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
- [object]#
EvalOnSelectorAllAsync
Added in: v1.9In 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
- [object]#
FillAsync
Added before v1.9Use 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
. -
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). Pass0
to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout() or Page.SetDefaultTimeout() methods.
-
Returns
FocusAsync
Added before v1.9Use 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). Pass0
to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout() or Page.SetDefaultTimeout() methods.
-
Returns
GetAttributeAsync
Added before v1.9Use 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). Pass0
to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout() or Page.SetDefaultTimeout() methods.
-
Returns
HoverAsync
Added before v1.9Use locator-based Locator.HoverAsync() instead. Read more about locators.
This method hovers over an element matching selector by performing the following steps:
- Find an element matching selector. If there is none, wait until a matching element is attached to the DOM.
- Wait for actionability checks on the matched element, unless Force option is set. If the element is detached during the checks, the whole action is retried.
- Scroll the element into view if needed.
- Use Page.Mouse to hover over the center of the element, or the specified Position.
When all steps combined have not finished during the specified Timeout, this method throws a TimeoutError. Passing zero timeout disables this.
Usage
await Page.HoverAsync(selector, options);
Arguments
-
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#DeprecatedThis 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). Pass0
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 keyboardmodifiers
will be pressed regardless oftrial
to allow testing elements which are only visible when those keys are pressed.
-
Returns
InnerHTMLAsync
Added before v1.9Use 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). Pass0
to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout() or Page.SetDefaultTimeout() methods.
-
Returns
InnerTextAsync
Added before v1.9Use 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). Pass0
to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout() or Page.SetDefaultTimeout() methods.
-
Returns
InputValueAsync
Added in: v1.13Use 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). Pass0
to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout() or Page.SetDefaultTimeout() methods.
-
Returns
IsCheckedAsync
Added before v1.9Use 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). Pass0
to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout() or Page.SetDefaultTimeout() methods.
-
Returns
IsDisabledAsync
Added before v1.9Use 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). Pass0
to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout() or Page.SetDefaultTimeout() methods.
-
Returns
IsEditableAsync
Added before v1.9Use 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). Pass0
to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout() or Page.SetDefaultTimeout() methods.
-
Returns
IsEnabledAsync
Added before v1.9Use 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). Pass0
to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout() or Page.SetDefaultTimeout() methods.
-
Returns
IsHiddenAsync
Added before v1.9Use 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)#DeprecatedThis option is ignored. Page.IsHiddenAsync() does not wait for the element to become hidden and returns immediately.
-
Returns
IsVisibleAsync
Added before v1.9Use 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)#DeprecatedThis option is ignored. Page.IsVisibleAsync() does not wait for the element to become visible and returns immediately.
-
Returns
PressAsync
Added before v1.9Use 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
ora
. -
options
PagePressOptions?
(optional)-
Delay
[float]? (optional)#Time to wait between
keydown
andkeyup
in milliseconds. Defaults to 0. -
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). Pass0
to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout() or Page.SetDefaultTimeout() methods.
-
Returns
QuerySelectorAsync
Added in: v1.9Use 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
QuerySelectorAllAsync
Added in: v1.9Use 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
RunAndWaitForNavigationAsync
Added before v1.9This 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
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 theDOMContentLoaded
event is fired.'load'
- consider operation to be finished when theload
event is fired.'networkidle'
- DISCOURAGED consider operation to be finished when there are no network connections for at least500
ms. Don't use this method for testing, rely on web assertions to assess readiness instead.'commit'
- consider operation to be finished when network response is received and the document started loading.
-
Returns
WaitForNavigationAsync
Added before v1.9This 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
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 theDOMContentLoaded
event is fired.'load'
- consider operation to be finished when theload
event is fired.'networkidle'
- DISCOURAGED consider operation to be finished when there are no network connections for at least500
ms. Don't use this method for testing, rely on web assertions to assess readiness instead.'commit'
- consider operation to be finished when network response is received and the document started loading.
-
Returns
SelectOptionAsync
Added before v1.9Use locator-based Locator.SelectOptionAsync() instead. Read more about locators.
This method waits for an element matching selector, waits for actionability checks, waits until all specified options are present in the <select>
element and selects these options.
If the target element is not a <select>
element, this method throws an error. However, if the element is inside the <label>
element that has an associated control, the control will be used instead.
Returns the array of option values that have been successfully selected.
Triggers a change
and input
event once all the provided options have been selected.
Usage
// Single selection matching the value or label
await page.SelectOptionAsync("select#colors", new[] { "blue" });
// single selection matching both the value and the label
await page.SelectOptionAsync("select#colors", new[] { new SelectOptionValue() { Label = "blue" } });
// multiple
await page.SelectOptionAsync("select#colors", new[] { "red", "green", "blue" });
Arguments
-
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 themultiple
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
. -
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). Pass0
to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout() or Page.SetDefaultTimeout() methods.
-
Returns
SetCheckedAsync
Added in: v1.15Use locator-based Locator.SetCheckedAsync() instead. Read more about locators.
This method checks or unchecks an element matching selector by performing the following steps:
- Find an element matching selector. If there is none, wait until a matching element is attached to the DOM.
- Ensure that matched element is a checkbox or a radio input. If not, this method throws.
- If the element already has the right checked state, this method returns immediately.
- Wait for actionability checks on the matched element, unless Force option is set. If the element is detached during the checks, the whole action is retried.
- Scroll the element into view if needed.
- Use Page.Mouse to click in the center of the element.
- Ensure that the element is now checked or unchecked. If not, this method throws.
When all steps combined have not finished during the specified Timeout, this method throws a TimeoutError. Passing zero timeout disables this.
Usage
await Page.SetCheckedAsync(selector, checked, options);
Arguments
-
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
. -
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). Pass0
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
SetInputFilesAsync
Added before v1.9Use 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)-
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). Pass0
to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout() or Page.SetDefaultTimeout() methods.
-
Returns
TapAsync
Added before v1.9Use locator-based Locator.TapAsync() instead. Read more about locators.
This method taps an element matching selector by performing the following steps:
- Find an element matching selector. If there is none, wait until a matching element is attached to the DOM.
- Wait for actionability checks on the matched element, unless Force option is set. If the element is detached during the checks, the whole action is retried.
- Scroll the element into view if needed.
- Use Page.Touchscreen to tap the center of the element, or the specified Position.
When all steps combined have not finished during the specified Timeout, this method throws a TimeoutError. Passing zero timeout disables this.
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.
-
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). Pass0
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 keyboardmodifiers
will be pressed regardless oftrial
to allow testing elements which are only visible when those keys are pressed.
-
Returns
TextContentAsync
Added before v1.9Use 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). Pass0
to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout() or Page.SetDefaultTimeout() methods.
-
Returns
TypeAsync
Added before v1.9In 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.
-
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). Pass0
to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout() or Page.SetDefaultTimeout() methods.
-
Returns
UncheckAsync
Added before v1.9Use locator-based Locator.UncheckAsync() instead. Read more about locators.
This method unchecks an element matching selector by performing the following steps:
- Find an element matching selector. If there is none, wait until a matching element is attached to the DOM.
- Ensure that matched element is a checkbox or a radio input. If not, this method throws. If the element is already unchecked, this method returns immediately.
- Wait for actionability checks on the matched element, unless Force option is set. If the element is detached during the checks, the whole action is retried.
- Scroll the element into view if needed.
- Use Page.Mouse to click in the center of the element.
- Ensure that the element is now unchecked. If not, this method throws.
When all steps combined have not finished during the specified Timeout, this method throws a TimeoutError. Passing zero timeout disables this.
Usage
await Page.UncheckAsync(selector, options);
Arguments
-
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
. -
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). Pass0
to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout() or Page.SetDefaultTimeout() methods. -
Trial
bool? (optional) Added in: v1.11#When set, this method only performs the actionability checks and skips the action. Defaults to
false
. Useful to wait until the element is ready for the action without performing it.
-
Returns
WaitForSelectorAsync
Added before v1.9Use 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
.
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 novisibility:hidden
. Note that element without any content or withdisplay: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 orvisibility: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). Pass0
to disable timeout. The default value can be changed by using the BrowserContext.SetDefaultTimeout() or Page.SetDefaultTimeout() methods.
-
Returns
WaitForTimeoutAsync
Added before v1.9Never wait for timeout in production. Tests that wait for time are inherently flaky. Use Locator actions and web assertions that wait automatically.
Waits for the given timeout in milliseconds.
Note that page.waitForTimeout()
should only be used for debugging. Tests using the timer in production are going to be flaky. Use signals such as network events, selectors becoming visible and others instead.
Usage
// Wait for 1 second
await page.WaitForTimeoutAsync(1000);
Arguments
-
timeout
[float]#A timeout to wait for
Returns