Interface IPage
- Namespace
- Microsoft.Playwright
- Assembly
- Microsoft.Playwright.dll
Page provides methods to interact with a single tab in a IBrowser, or an extension background page in Chromium. One IBrowser instance might have multiple IPage 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;
public interface IPage
Properties
APIRequest
API testing helper associated with this page. This method returns the same instance as APIRequest on the page's context. See APIRequest for more details.
IAPIRequestContext APIRequest { get; }
Property Value
Accessibility
**DEPRECATED** This property is discouraged. Please use other libraries such as Axe if you need to test page accessibility. See our Node.js guide for integration with Axe.
[Obsolete]
IAccessibility Accessibility { get; }
Property Value
Clock
Playwright has ability to mock clock and passage of time.
IClock Clock { get; }
Property Value
Context
Get the browser context that the page belongs to.
IBrowserContext Context { get; }
Property Value
Frames
An array of all frames attached to the page.
IReadOnlyList<IFrame> Frames { get; }
Property Value
IsClosed
Indicates that the page has been closed.
bool IsClosed { get; }
Property Value
Keyboard
IKeyboard Keyboard { get; }
Property Value
MainFrame
The page's main frame. Page is guaranteed to have a main frame which persists during navigations.
IFrame MainFrame { get; }
Property Value
Mouse
IMouse Mouse { get; }
Property Value
Touchscreen
ITouchscreen Touchscreen { get; }
Property Value
Url
string Url { get; }
Property Value
Video
Video object associated with this page.
IVideo? Video { get; }
Property Value
ViewportSize
PageViewportSizeResult? ViewportSize { get; }
Property Value
Workers
This method returns all of the dedicated WebWorkers associated with the page.
IReadOnlyList<IWorker> Workers { get; }
Property Value
Remarks
This does not contain ServiceWorkers
Methods
AddInitScriptAsync(string?, string?)
Adds a script which would be evaluated in one of the following scenarios:
- Whenever the page is navigated.
- Whenever the child frame is attached or navigated. In this case, the script is evaluated in the context of the newly attached frame.
The script is evaluated after the document was created but before any of its scripts
were run. This is useful to amend the JavaScript environment, e.g. to seed Math.random
.
**Usage**
An example of overriding Math.random
before the page loads:
await Page.AddInitScriptAsync(scriptPath: "./preload.js");
Task AddInitScriptAsync(string? script = null, string? scriptPath = null)
Parameters
script
stringScript to be evaluated in all pages in the browser context.
scriptPath
stringInstead of specifying
script
, gives the file name to load from.
Returns
Remarks
The order of evaluation of multiple scripts installed via AddInitScriptAsync(string?, string?) and AddInitScriptAsync(string?, string?) is not defined.
AddLocatorHandlerAsync(ILocator, Func<ILocator, Task>, PageAddLocatorHandlerOptions?)
When testing a web page, sometimes unexpected overlays like a "Sign up" dialog appear and block actions you want to automate, e.g. clicking a button. These overlays don't always show up in the same way or at the same time, making them tricky to handle in automated tests.
This method lets you set up a special function, called a handler, that activates when it detects that overlay is visible. The handler's job is to remove the overlay, allowing your test to continue as if the overlay wasn't there.
Things to keep in mind:
- When an overlay is shown predictably, we recommend explicitly waiting for it in your test and dismissing it as a part of your normal test flow, instead of using AddLocatorHandlerAsync(ILocator, Func<ILocator, Task>, PageAddLocatorHandlerOptions?).
- 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.
**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 });
Task AddLocatorHandlerAsync(ILocator locator, Func<ILocator, Task> handler, PageAddLocatorHandlerOptions? options = null)
Parameters
locator
ILocatorLocator that triggers the handler.
handler
Func<ILocator, Task>Function that should be run once
locator
appears. This function should get rid of the element that blocks actions like click.options
PageAddLocatorHandlerOptionsCall options
Returns
Remarks
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 FocusAsync(LocatorFocusOptions?)
followed by PressAsync(string, KeyboardPressOptions?). 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 PressAsync(string, LocatorPressOptions?)
instead to avoid this problem.
Another example is a series of mouse
actions, where MoveAsync(float, float, MouseMoveOptions?) is followed by DownAsync(MouseDownOptions?).
Again, when the handler runs between these two actions, the mouse position will
be wrong during the mouse down. Prefer self-contained actions like ClickAsync(LocatorClickOptions?)
that do not rely on the state being unchanged by a handler.
AddLocatorHandlerAsync(ILocator, Func<Task>, PageAddLocatorHandlerOptions?)
Task AddLocatorHandlerAsync(ILocator locator, Func<Task> handler, PageAddLocatorHandlerOptions? options = null)
Parameters
locator
ILocatorhandler
Func<Task>options
PageAddLocatorHandlerOptions
Returns
AddScriptTagAsync(PageAddScriptTagOptions?)
Adds a <script>
tag into the page with the desired url or content.
Returns the added tag when the script's onload fires or when the script content
was injected into frame.
Task<IElementHandle> AddScriptTagAsync(PageAddScriptTagOptions? options = null)
Parameters
options
PageAddScriptTagOptionsCall options
Returns
AddStyleTagAsync(PageAddStyleTagOptions?)
Adds a <link rel="stylesheet">
tag into the page with the desired url
or a <style type="text/css">
tag with the content. Returns the added
tag when the stylesheet's onload fires or when the CSS content was injected into
frame.
Task<IElementHandle> AddStyleTagAsync(PageAddStyleTagOptions? options = null)
Parameters
options
PageAddStyleTagOptionsCall options
Returns
BringToFrontAsync()
Brings page to front (activates tab).
Task BringToFrontAsync()
Returns
CheckAsync(string, PageCheckOptions?)
Use locator-based CheckAsync(LocatorCheckOptions?) instead. Read more about locators.
This method checks an element matching selector
by performing
the following steps:
When all steps combined have not finished during the specified timeout
,
this method throws a TimeoutException. Passing zero timeout disables
this.
Task CheckAsync(string selector, PageCheckOptions? options = null)
Parameters
selector
stringA selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
options
PageCheckOptionsCall options
Returns
ClickAsync(string, PageClickOptions?)
Use locator-based ClickAsync(LocatorClickOptions?) instead. Read more about locators.
This method clicks an element matching selector
by performing
the following steps:
When all steps combined have not finished during the specified timeout
,
this method throws a TimeoutException. Passing zero timeout disables
this.
Task ClickAsync(string selector, PageClickOptions? options = null)
Parameters
selector
stringA selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
options
PageClickOptionsCall options
Returns
CloseAsync(PageCloseOptions?)
If runBeforeUnload
is false
, does not run any unload handlers
and waits for the page to be closed. If runBeforeUnload
is true
the method will run unload handlers, but will **not** wait for the page to close.
By default, page.close()
**does not** run beforeunload
handlers.
Task CloseAsync(PageCloseOptions? options = null)
Parameters
options
PageCloseOptionsCall options
Returns
Remarks
if runBeforeUnload
is passed as true, a beforeunload
dialog
might be summoned and should be handled manually via Dialog
event.
ContentAsync()
Gets the full HTML contents of the page, including the doctype.
Task<string> ContentAsync()
Returns
DblClickAsync(string, PageDblClickOptions?)
Use locator-based DblClickAsync(LocatorDblClickOptions?) instead. Read more about locators.
This method double clicks an element matching selector
by performing
the following steps:
When all steps combined have not finished during the specified timeout
,
this method throws a TimeoutException. Passing zero timeout disables
this.
Task DblClickAsync(string selector, PageDblClickOptions? options = null)
Parameters
selector
stringA selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
options
PageDblClickOptionsCall options
Returns
Remarks
page.dblclick()
dispatches two click
events and a single dblclick
event.
DispatchEventAsync(string, string, object?, PageDispatchEventOptions?)
Use locator-based DispatchEventAsync(string, object?, LocatorDispatchEventOptions?) 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 });
Task DispatchEventAsync(string selector, string type, object? eventInit = null, PageDispatchEventOptions? options = null)
Parameters
selector
stringA selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
type
stringDOM event type:
"click"
,"dragstart"
, etc.eventInit
objectOptional event-specific initialization properties.
options
PageDispatchEventOptionsCall options
Returns
DragAndDropAsync(string, string, PageDragAndDropOptions?)
This method drags the source element to the target element. It will first move to
the source element, perform a mousedown
, then move to the target element
and perform a mouseup
.
**Usage**
await Page.DragAndDropAsync("#source", "#target");
// or specify exact positions relative to the top-left corners of the elements:
await Page.DragAndDropAsync("#source", "#target", new()
{
SourcePosition = new() { X = 34, Y = 7 },
TargetPosition = new() { X = 10, Y = 20 },
});
Task DragAndDropAsync(string source, string target, PageDragAndDropOptions? options = null)
Parameters
source
stringA selector to search for an element to drag. If there are multiple elements satisfying the selector, the first will be used.
target
stringA selector to search for an element to drop onto. If there are multiple elements satisfying the selector, the first will be used.
options
PageDragAndDropOptionsCall options
Returns
EmulateMediaAsync(PageEmulateMediaOptions?)
This method changes the CSS media type
through the media
argument,
and/or the 'prefers-colors-scheme'
media feature, using the colorScheme
argument.
**Usage**
await page.EvaluateAsync("() => matchMedia('screen').matches");
// → true
await page.EvaluateAsync("() => matchMedia('print').matches");
// → false
await page.EmulateMediaAsync(new() { Media = Media.Print });
await page.EvaluateAsync("() => matchMedia('screen').matches");
// → false
await page.EvaluateAsync("() => matchMedia('print').matches");
// → true
await page.EmulateMediaAsync(new() { Media = Media.Screen });
await page.EvaluateAsync("() => matchMedia('screen').matches");
// → true
await page.EvaluateAsync("() => matchMedia('print').matches");
// → false
await page.EmulateMediaAsync(new() { ColorScheme = ColorScheme.Dark });
await page.EvaluateAsync("matchMedia('(prefers-color-scheme: dark)').matches");
// → true
await page.EvaluateAsync("matchMedia('(prefers-color-scheme: light)').matches");
// → false
await page.EvaluateAsync("matchMedia('(prefers-color-scheme: no-preference)').matches");
// → false
Task EmulateMediaAsync(PageEmulateMediaOptions? options = null)
Parameters
options
PageEmulateMediaOptionsCall options
Returns
EvalOnSelectorAllAsync(string, string, object?)
Task<JsonElement?> EvalOnSelectorAllAsync(string selector, string expression, object? arg = null)
Parameters
Returns
EvalOnSelectorAllAsync<T>(string, string, object?)
In most cases, EvaluateAllAsync<T>(string, object?), other ILocator 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 Task, then EvalOnSelectorAllAsync(string, string, object?)
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);
Task<T> EvalOnSelectorAllAsync<T>(string selector, string expression, object? arg = null)
Parameters
selector
stringA selector to query for.
expression
stringJavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the function is automatically invoked.
arg
objectOptional argument to pass to
expression
.
Returns
- Task<T>
Type Parameters
T
EvalOnSelectorAsync(string, string, object?)
Task<JsonElement?> EvalOnSelectorAsync(string selector, string expression, object? arg = null)
Parameters
Returns
EvalOnSelectorAsync<T>(string, string, object?, PageEvalOnSelectorOptions?)
This method does not wait for the element to pass actionability checks and therefore can lead to the flaky tests. Use EvaluateAsync(string, object, LocatorEvaluateOptions), other ILocator 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 Task, then EvalOnSelectorAsync(string, string, object?)
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");
Task<T> EvalOnSelectorAsync<T>(string selector, string expression, object? arg = null, PageEvalOnSelectorOptions? options = null)
Parameters
selector
stringA selector to query for.
expression
stringJavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the function is automatically invoked.
arg
objectOptional argument to pass to
expression
.options
PageEvalOnSelectorOptionsCall options
Returns
- Task<T>
Type Parameters
T
EvaluateAsync(string, object?)
Task<JsonElement?> EvaluateAsync(string expression, object? arg = null)
Parameters
Returns
EvaluateAsync<T>(string, object?)
Returns the value of the expression
invocation.
If the function passed to the EvaluateAsync(string, object?) returns a Task, then EvaluateAsync(string, object?) would wait for the promise to resolve and return its value.
If the function passed to the EvaluateAsync(string, object?) returns a non-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"
IElementHandle instances can be passed as an argument to the EvaluateAsync(string, object?):
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();
Task<T> EvaluateAsync<T>(string expression, object? arg = null)
Parameters
expression
stringJavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the function is automatically invoked.
arg
objectOptional argument to pass to
expression
.
Returns
- Task<T>
Type Parameters
T
EvaluateHandleAsync(string, object?)
Returns the value of the expression
invocation as a IJSHandle.
The only difference between EvaluateAsync(string, object?) and EvaluateHandleAsync(string, object?) is that EvaluateHandleAsync(string, object?) returns IJSHandle.
If the function passed to the EvaluateHandleAsync(string, object?) returns a Task, then EvaluateHandleAsync(string, object?) 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`
IJSHandle instances can be passed as an argument to the EvaluateHandleAsync(string, object?):
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();
Task<IJSHandle> EvaluateHandleAsync(string expression, object? arg = null)
Parameters
expression
stringJavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the function is automatically invoked.
arg
objectOptional argument to pass to
expression
.
Returns
ExposeBindingAsync(string, Action, PageExposeBindingOptions?)
The method adds a function called name
on the window
object
of every frame in this page. When called, the function executes callback
and returns a Task which resolves to the return value of callback
. If the callback
returns a
The first argument of the callback
function contains information
about the caller: { browserContext: BrowserContext, page: Page, frame: Frame
}
.
See ExposeBindingAsync(string, Action, BrowserContextExposeBindingOptions?) for the context-wide version.
**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");
}
}
Task ExposeBindingAsync(string name, Action callback, PageExposeBindingOptions? options = null)
Parameters
name
stringName of the function on the window object.
callback
ActionCallback function that will be called in the Playwright's context.
options
PageExposeBindingOptionsCall options
Returns
Remarks
Functions installed via ExposeBindingAsync(string, Action, PageExposeBindingOptions?) survive navigations.
ExposeBindingAsync(string, Action<BindingSource>)
Task ExposeBindingAsync(string name, Action<BindingSource> callback)
Parameters
name
stringcallback
Action<BindingSource>
Returns
ExposeBindingAsync<T>(string, Action<BindingSource, T>)
Task ExposeBindingAsync<T>(string name, Action<BindingSource, T> callback)
Parameters
name
stringcallback
Action<BindingSource, T>
Returns
Type Parameters
T
ExposeBindingAsync<TResult>(string, Func<BindingSource, IJSHandle, TResult>)
Task ExposeBindingAsync<TResult>(string name, Func<BindingSource, IJSHandle, TResult> callback)
Parameters
name
stringcallback
Func<BindingSource, IJSHandle, TResult>
Returns
Type Parameters
TResult
ExposeBindingAsync<TResult>(string, Func<BindingSource, TResult>)
Task ExposeBindingAsync<TResult>(string name, Func<BindingSource, TResult> callback)
Parameters
name
stringcallback
Func<BindingSource, TResult>
Returns
Type Parameters
TResult
ExposeBindingAsync<T, TResult>(string, Func<BindingSource, T, TResult>)
Task ExposeBindingAsync<T, TResult>(string name, Func<BindingSource, T, TResult> callback)
Parameters
name
stringcallback
Func<BindingSource, T, TResult>
Returns
Type Parameters
T
TResult
ExposeBindingAsync<T1, T2, TResult>(string, Func<BindingSource, T1, T2, TResult>)
Task ExposeBindingAsync<T1, T2, TResult>(string name, Func<BindingSource, T1, T2, TResult> callback)
Parameters
name
stringcallback
Func<BindingSource, T1, T2, TResult>
Returns
Type Parameters
T1
T2
TResult
ExposeBindingAsync<T1, T2, T3, TResult>(string, Func<BindingSource, T1, T2, T3, TResult>)
Task ExposeBindingAsync<T1, T2, T3, TResult>(string name, Func<BindingSource, T1, T2, T3, TResult> callback)
Parameters
name
stringcallback
Func<BindingSource, T1, T2, T3, TResult>
Returns
Type Parameters
T1
T2
T3
TResult
ExposeBindingAsync<T1, T2, T3, T4, TResult>(string, Func<BindingSource, T1, T2, T3, T4, TResult>)
Task ExposeBindingAsync<T1, T2, T3, T4, TResult>(string name, Func<BindingSource, T1, T2, T3, T4, TResult> callback)
Parameters
name
stringcallback
Func<BindingSource, T1, T2, T3, T4, TResult>
Returns
Type Parameters
T1
T2
T3
T4
TResult
ExposeFunctionAsync(string, Action)
The method adds a function called name
on the window
object
of every frame in the page. When called, the function executes callback
and returns a Task which resolves to the return value of callback
.
If the callback
returns a Task, it will be awaited.
See ExposeFunctionAsync(string, Action) for context-wide exposed function.
**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"));
}
}
Task ExposeFunctionAsync(string name, Action callback)
Parameters
name
stringName of the function on the window object
callback
ActionCallback function which will be called in Playwright's context.
Returns
Remarks
Functions installed via ExposeFunctionAsync(string, Action) survive navigations.
ExposeFunctionAsync<T>(string, Action<T>)
Task ExposeFunctionAsync<T>(string name, Action<T> callback)
Parameters
Returns
Type Parameters
T
ExposeFunctionAsync<TResult>(string, Func<TResult>)
Task ExposeFunctionAsync<TResult>(string name, Func<TResult> callback)
Parameters
Returns
Type Parameters
TResult
ExposeFunctionAsync<T, TResult>(string, Func<T, TResult>)
Task ExposeFunctionAsync<T, TResult>(string name, Func<T, TResult> callback)
Parameters
Returns
Type Parameters
T
TResult
ExposeFunctionAsync<T1, T2, TResult>(string, Func<T1, T2, TResult>)
Task ExposeFunctionAsync<T1, T2, TResult>(string name, Func<T1, T2, TResult> callback)
Parameters
Returns
Type Parameters
T1
T2
TResult
ExposeFunctionAsync<T1, T2, T3, TResult>(string, Func<T1, T2, T3, TResult>)
Task ExposeFunctionAsync<T1, T2, T3, TResult>(string name, Func<T1, T2, T3, TResult> callback)
Parameters
Returns
Type Parameters
T1
T2
T3
TResult
ExposeFunctionAsync<T1, T2, T3, T4, TResult>(string, Func<T1, T2, T3, T4, TResult>)
Task ExposeFunctionAsync<T1, T2, T3, T4, TResult>(string name, Func<T1, T2, T3, T4, TResult> callback)
Parameters
Returns
Type Parameters
T1
T2
T3
T4
TResult
FillAsync(string, string, PageFillOptions?)
Use locator-based FillAsync(string, LocatorFillOptions?) 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 PressSequentiallyAsync(string, LocatorPressSequentiallyOptions?).
Task FillAsync(string selector, string value, PageFillOptions? options = null)
Parameters
selector
stringA selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
value
stringValue to fill for the
<input>
,<textarea>
or[contenteditable]
element.options
PageFillOptionsCall options
Returns
FocusAsync(string, PageFocusOptions?)
Use locator-based FocusAsync(LocatorFocusOptions?) 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.
Task FocusAsync(string selector, PageFocusOptions? options = null)
Parameters
selector
stringA selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
options
PageFocusOptionsCall options
Returns
Frame(string)
Returns frame matching the specified criteria. Either name
or url
must be specified.
**Usage**
var frame = page.Frame("frame-name");
var frame = page.FrameByUrl(".*domain.*");
IFrame? Frame(string name)
Parameters
name
stringFrame name specified in the
iframe
'sname
attribute.
Returns
FrameByUrl(Func<string, bool>)
Returns frame with matching URL.
IFrame? FrameByUrl(Func<string, bool> url)
Parameters
url
Func<string, bool>A glob pattern, regex pattern or predicate receiving frame's
url
as aobject.
Returns
FrameByUrl(string)
Returns frame with matching URL.
IFrame? FrameByUrl(string url)
Parameters
url
stringA glob pattern, regex pattern or predicate receiving frame's
url
as aobject.
Returns
FrameByUrl(Regex)
Returns frame with matching URL.
IFrame? FrameByUrl(Regex url)
Parameters
url
RegexA glob pattern, regex pattern or predicate receiving frame's
url
as aobject.
Returns
FrameLocator(string)
When working with iframes, you can create a frame locator that will enter the iframe and allow selecting elements in that iframe.
**Usage**
Following snippet locates element with text "Submit" in the iframe with id my-frame
,
like <iframe id="my-frame">
:
var locator = page.FrameLocator("#my-iframe").GetByText("Submit");
await locator.ClickAsync();
IFrameLocator FrameLocator(string selector)
Parameters
selector
stringA selector to use when resolving DOM element.
Returns
GetAttributeAsync(string, string, PageGetAttributeOptions?)
Use locator-based GetAttributeAsync(string, LocatorGetAttributeOptions?) instead. Read more about locators.
Returns element attribute value.
Task<string?> GetAttributeAsync(string selector, string name, PageGetAttributeOptions? options = null)
Parameters
selector
stringA selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
name
stringAttribute name to get the value for.
options
PageGetAttributeOptionsCall options
Returns
GetByAltText(string, PageGetByAltTextOptions?)
Allows locating elements by their alt text.
**Usage**
For example, this method will find the image by alt text "Playwright logo":
await page.GetByAltText("Playwright logo").ClickAsync();
ILocator GetByAltText(string text, PageGetByAltTextOptions? options = null)
Parameters
text
stringText to locate the element for.
options
PageGetByAltTextOptionsCall options
Returns
GetByAltText(Regex, PageGetByAltTextOptions?)
Allows locating elements by their alt text.
**Usage**
For example, this method will find the image by alt text "Playwright logo":
await page.GetByAltText("Playwright logo").ClickAsync();
ILocator GetByAltText(Regex text, PageGetByAltTextOptions? options = null)
Parameters
text
RegexText to locate the element for.
options
PageGetByAltTextOptionsCall options
Returns
GetByLabel(string, PageGetByLabelOptions?)
Allows locating input elements by the text of the associated <label>
or aria-labelledby
element, or by the aria-label
attribute.
**Usage**
For example, this method will find inputs by label "Username" and "Password" in the following DOM:
await page.GetByLabel("Username").FillAsync("john");
await page.GetByLabel("Password").FillAsync("secret");
ILocator GetByLabel(string text, PageGetByLabelOptions? options = null)
Parameters
text
stringText to locate the element for.
options
PageGetByLabelOptionsCall options
Returns
GetByLabel(Regex, PageGetByLabelOptions?)
Allows locating input elements by the text of the associated <label>
or aria-labelledby
element, or by the aria-label
attribute.
**Usage**
For example, this method will find inputs by label "Username" and "Password" in the following DOM:
await page.GetByLabel("Username").FillAsync("john");
await page.GetByLabel("Password").FillAsync("secret");
ILocator GetByLabel(Regex text, PageGetByLabelOptions? options = null)
Parameters
text
RegexText to locate the element for.
options
PageGetByLabelOptionsCall options
Returns
GetByPlaceholder(string, PageGetByPlaceholderOptions?)
Allows locating input elements by the placeholder text.
**Usage**
For example, consider the following DOM structure.
You can fill the input after locating it by the placeholder text:
await page
.GetByPlaceholder("name@example.com")
.FillAsync("playwright@microsoft.com");
ILocator GetByPlaceholder(string text, PageGetByPlaceholderOptions? options = null)
Parameters
text
stringText to locate the element for.
options
PageGetByPlaceholderOptionsCall options
Returns
GetByPlaceholder(Regex, PageGetByPlaceholderOptions?)
Allows locating input elements by the placeholder text.
**Usage**
For example, consider the following DOM structure.
You can fill the input after locating it by the placeholder text:
await page
.GetByPlaceholder("name@example.com")
.FillAsync("playwright@microsoft.com");
ILocator GetByPlaceholder(Regex text, PageGetByPlaceholderOptions? options = null)
Parameters
text
RegexText to locate the element for.
options
PageGetByPlaceholderOptionsCall options
Returns
GetByRole(AriaRole, PageGetByRoleOptions?)
Allows locating elements by their ARIA role, ARIA attributes and accessible name.
**Usage**
Consider the following DOM structure.
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();
**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.
ILocator GetByRole(AriaRole role, PageGetByRoleOptions? options = null)
Parameters
role
AriaRoleRequired aria role.
options
PageGetByRoleOptionsCall options
Returns
GetByTestId(string)
Locate element by the test id.
**Usage**
Consider the following DOM structure.
You can locate the element by it's test id:
await page.GetByTestId("directions").ClickAsync();
**Details**
By default, the data-testid
attribute is used as a test id. Use SetTestIdAttribute(string)
to configure a different test id attribute if necessary.
ILocator GetByTestId(string testId)
Parameters
testId
stringId to locate the element by.
Returns
GetByTestId(Regex)
Locate element by the test id.
**Usage**
Consider the following DOM structure.
You can locate the element by it's test id:
await page.GetByTestId("directions").ClickAsync();
**Details**
By default, the data-testid
attribute is used as a test id. Use SetTestIdAttribute(string)
to configure a different test id attribute if necessary.
ILocator GetByTestId(Regex testId)
Parameters
testId
RegexId to locate the element by.
Returns
GetByText(string, PageGetByTextOptions?)
Allows locating elements that contain given text.
See also Filter(LocatorFilterOptions?) that allows to match by another criteria, like an accessible role, and then filter by the text content.
**Usage**
Consider the following DOM structure:
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));
**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">
.
ILocator GetByText(string text, PageGetByTextOptions? options = null)
Parameters
text
stringText to locate the element for.
options
PageGetByTextOptionsCall options
Returns
GetByText(Regex, PageGetByTextOptions?)
Allows locating elements that contain given text.
See also Filter(LocatorFilterOptions?) that allows to match by another criteria, like an accessible role, and then filter by the text content.
**Usage**
Consider the following DOM structure:
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));
**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">
.
ILocator GetByText(Regex text, PageGetByTextOptions? options = null)
Parameters
text
RegexText to locate the element for.
options
PageGetByTextOptionsCall options
Returns
GetByTitle(string, PageGetByTitleOptions?)
Allows locating elements by their title attribute.
**Usage**
Consider the following DOM structure.
You can check the issues count after locating it by the title text:
await Expect(Page.GetByTitle("Issues count")).toHaveText("25 issues");
ILocator GetByTitle(string text, PageGetByTitleOptions? options = null)
Parameters
text
stringText to locate the element for.
options
PageGetByTitleOptionsCall options
Returns
GetByTitle(Regex, PageGetByTitleOptions?)
Allows locating elements by their title attribute.
**Usage**
Consider the following DOM structure.
You can check the issues count after locating it by the title text:
await Expect(Page.GetByTitle("Issues count")).toHaveText("25 issues");
ILocator GetByTitle(Regex text, PageGetByTitleOptions? options = null)
Parameters
text
RegexText to locate the element for.
options
PageGetByTitleOptionsCall options
Returns
GoBackAsync(PageGoBackOptions?)
Returns the main resource response. In case of multiple redirects, the navigation
will resolve with the response of the last redirect. If can not go back, returns
null
.
Navigate to the previous page in history.
Task<IResponse?> GoBackAsync(PageGoBackOptions? options = null)
Parameters
options
PageGoBackOptionsCall options
Returns
GoForwardAsync(PageGoForwardOptions?)
Returns the main resource response. In case of multiple redirects, the navigation
will resolve with the response of the last redirect. If can not go forward, returns
null
.
Navigate to the next page in history.
Task<IResponse?> GoForwardAsync(PageGoForwardOptions? options = null)
Parameters
options
PageGoForwardOptionsCall options
Returns
GotoAsync(string, PageGotoOptions?)
Returns the main resource response. In case of multiple redirects, the navigation will resolve with the first non-redirect response.
The method will throw an error if:
- there's an SSL error (e.g. in case of self-signed certificates).
- target URL is invalid.
- the
timeout
is exceeded during navigation. - the remote server does not respond or is unreachable.
- the main resource failed to load.
The method will not throw an error when any valid HTTP status code is returned by the remote server, including 404 "Not Found" and 500 "Internal Server Error". The status code for such responses can be retrieved by calling Status.
Task<IResponse?> GotoAsync(string url, PageGotoOptions? options = null)
Parameters
url
stringURL to navigate page to. The url should include scheme, e.g.
https://
. When abaseURL
via the context options was provided and the passed URL is a path, it gets merged via thenew URL()
constructor.options
PageGotoOptionsCall options
Returns
Remarks
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.
HoverAsync(string, PageHoverOptions?)
Use locator-based HoverAsync(LocatorHoverOptions?) instead. Read more about locators.
This method hovers over an element matching selector
by performing
the following steps:
When all steps combined have not finished during the specified timeout
,
this method throws a TimeoutException. Passing zero timeout disables
this.
Task HoverAsync(string selector, PageHoverOptions? options = null)
Parameters
selector
stringA selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
options
PageHoverOptionsCall options
Returns
InnerHTMLAsync(string, PageInnerHTMLOptions?)
Use locator-based InnerHTMLAsync(LocatorInnerHTMLOptions?) instead. Read more about locators.
Returns element.innerHTML
.
Task<string> InnerHTMLAsync(string selector, PageInnerHTMLOptions? options = null)
Parameters
selector
stringA selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
options
PageInnerHTMLOptionsCall options
Returns
InnerTextAsync(string, PageInnerTextOptions?)
Use locator-based InnerTextAsync(LocatorInnerTextOptions?) instead. Read more about locators.
Returns element.innerText
.
Task<string> InnerTextAsync(string selector, PageInnerTextOptions? options = null)
Parameters
selector
stringA selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
options
PageInnerTextOptionsCall options
Returns
InputValueAsync(string, PageInputValueOptions?)
Use locator-based InputValueAsync(LocatorInputValueOptions?) 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.
Task<string> InputValueAsync(string selector, PageInputValueOptions? options = null)
Parameters
selector
stringA selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
options
PageInputValueOptionsCall options
Returns
IsCheckedAsync(string, PageIsCheckedOptions?)
Use locator-based IsCheckedAsync(LocatorIsCheckedOptions?) instead. Read more about locators.
Returns whether the element is checked. Throws if the element is not a checkbox or radio input.
Task<bool> IsCheckedAsync(string selector, PageIsCheckedOptions? options = null)
Parameters
selector
stringA selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
options
PageIsCheckedOptionsCall options
Returns
IsDisabledAsync(string, PageIsDisabledOptions?)
Use locator-based IsDisabledAsync(LocatorIsDisabledOptions?) instead. Read more about locators.
Returns whether the element is disabled, the opposite of enabled.
Task<bool> IsDisabledAsync(string selector, PageIsDisabledOptions? options = null)
Parameters
selector
stringA selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
options
PageIsDisabledOptionsCall options
Returns
IsEditableAsync(string, PageIsEditableOptions?)
Use locator-based IsEditableAsync(LocatorIsEditableOptions?) instead. Read more about locators.
Returns whether the element is editable.
Task<bool> IsEditableAsync(string selector, PageIsEditableOptions? options = null)
Parameters
selector
stringA selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
options
PageIsEditableOptionsCall options
Returns
IsEnabledAsync(string, PageIsEnabledOptions?)
Use locator-based IsEnabledAsync(LocatorIsEnabledOptions?) instead. Read more about locators.
Returns whether the element is enabled.
Task<bool> IsEnabledAsync(string selector, PageIsEnabledOptions? options = null)
Parameters
selector
stringA selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
options
PageIsEnabledOptionsCall options
Returns
IsHiddenAsync(string, PageIsHiddenOptions?)
Use locator-based IsHiddenAsync(LocatorIsHiddenOptions?) 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.
Task<bool> IsHiddenAsync(string selector, PageIsHiddenOptions? options = null)
Parameters
selector
stringA selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
options
PageIsHiddenOptionsCall options
Returns
IsVisibleAsync(string, PageIsVisibleOptions?)
Use locator-based IsVisibleAsync(LocatorIsVisibleOptions?) instead. Read more about locators.
Returns whether the element is visible.
selector
that does not match any elements is considered not visible.
Task<bool> IsVisibleAsync(string selector, PageIsVisibleOptions? options = null)
Parameters
selector
stringA selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
options
PageIsVisibleOptionsCall options
Returns
Locator(string, PageLocatorOptions?)
The method returns an element locator that can be used to perform actions on this page / frame. Locator is resolved to the element immediately before performing an action, so a series of actions on the same locator can in fact be performed on different DOM elements. That would happen if the DOM structure between those actions has changed.
ILocator Locator(string selector, PageLocatorOptions? options = null)
Parameters
selector
stringA selector to use when resolving DOM element.
options
PageLocatorOptionsCall options
Returns
OpenerAsync()
Returns the opener for popup pages and null
for others. If the opener has
been closed already the returns null
.
Task<IPage?> OpenerAsync()
Returns
PauseAsync()
Pauses script execution. Playwright will stop executing the script and wait for
the user to either press 'Resume' button in the page overlay or to call playwright.resume()
in the DevTools console.
User can inspect selectors or perform manual steps while paused. Resume will continue running the original script from the place it was paused.
Task PauseAsync()
Returns
Remarks
This method requires Playwright to be started in a headed mode, with a falsy headless
value in the LaunchAsync(BrowserTypeLaunchOptions?).
PdfAsync(PagePdfOptions?)
Returns the PDF buffer.
page.pdf()
generates a pdf of the page with print
css media. To generate
a pdf with screen
media, call EmulateMediaAsync(PageEmulateMediaOptions?) before
calling page.pdf()
:
**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
Task<byte[]> PdfAsync(PagePdfOptions? options = null)
Parameters
options
PagePdfOptionsCall options
Returns
Remarks
Generating a pdf is currently only supported in Chromium headless.
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.
headerTemplate
and footerTemplate
markup have
the following limitations: > 1. Script tags inside templates are not evaluated.
> 2. Page styles are not visible inside templates.
PressAsync(string, string, PagePressOptions?)
Use locator-based PressAsync(string, LocatorPressOptions?) instead. Read more about locators.
Focuses the element, and then uses DownAsync(string) and UpAsync(string).
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" });
Task PressAsync(string selector, string key, PagePressOptions? options = null)
Parameters
selector
stringA selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
key
stringName of the key to press or a character to generate, such as
ArrowLeft
ora
.options
PagePressOptionsCall options
Returns
QuerySelectorAllAsync(string)
Use locator-based Locator(string, PageLocatorOptions?) 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 []
.
Task<IReadOnlyList<IElementHandle>> QuerySelectorAllAsync(string selector)
Parameters
selector
stringA selector to query for.
Returns
QuerySelectorAsync(string, PageQuerySelectorOptions?)
Use locator-based Locator(string, PageLocatorOptions?) 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 WaitForAsync(LocatorWaitForOptions?).
Task<IElementHandle?> QuerySelectorAsync(string selector, PageQuerySelectorOptions? options = null)
Parameters
selector
stringA selector to query for.
options
PageQuerySelectorOptionsCall options
Returns
ReloadAsync(PageReloadOptions?)
This method reloads the current page, in the same way as if the user had triggered a browser refresh. Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect.
Task<IResponse?> ReloadAsync(PageReloadOptions? options = null)
Parameters
options
PageReloadOptionsCall options
Returns
RemoveLocatorHandlerAsync(ILocator)
Removes all locator handlers added by AddLocatorHandlerAsync(ILocator, Func<ILocator, Task>, PageAddLocatorHandlerOptions?) for a specific locator.
Task RemoveLocatorHandlerAsync(ILocator locator)
Parameters
locator
ILocatorLocator passed to AddLocatorHandlerAsync(ILocator, Func<ILocator, Task>, PageAddLocatorHandlerOptions?).
Returns
RouteAsync(Func<string, bool>, Action<IRoute>, PageRouteOptions?)
Routing provides the capability to modify network requests that are made by a page.
Once routing is enabled, every request matching the url pattern will stall unless it's continued, fulfilled or aborted.
**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 RouteAsync(string, Action<IRoute>, BrowserContextRouteOptions?)) when request matches both handlers.
To remove a route with its handler you can use UnrouteAsync(string, Action<IRoute>?).
Task RouteAsync(Func<string, bool> url, Action<IRoute> handler, PageRouteOptions? options = null)
Parameters
url
Func<string, bool>A glob pattern, regex pattern or predicate receiving
to match while routing. When a baseURL
via the context options was provided and the passed URL is a path, it gets merged via thenew URL()
constructor.handler
Action<IRoute>handler function to route the request.
options
PageRouteOptionsCall options
Returns
Remarks
The handler will only be called for the first url if the response is a redirect.
RouteAsync(string, Action<IRoute>, PageRouteOptions?) will not intercept requests intercepted by Service
Worker. See this
issue. We recommend disabling Service Workers when using request interception by
setting Browser.newContext.serviceWorkers.newContext.serviceWorkers
to 'block'
.
RouteAsync(string, Action<IRoute>, PageRouteOptions?) will not intercept the first request of a popup page. Use RouteAsync(string, Action<IRoute>, BrowserContextRouteOptions?) instead.
Enabling routing disables http cache.
RouteAsync(Func<string, bool>, Func<IRoute, Task>, PageRouteOptions?)
Task RouteAsync(Func<string, bool> url, Func<IRoute, Task> handler, PageRouteOptions? options = null)
Parameters
Returns
RouteAsync(string, Action<IRoute>, PageRouteOptions?)
Routing provides the capability to modify network requests that are made by a page.
Once routing is enabled, every request matching the url pattern will stall unless it's continued, fulfilled or aborted.
**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 RouteAsync(string, Action<IRoute>, BrowserContextRouteOptions?)) when request matches both handlers.
To remove a route with its handler you can use UnrouteAsync(string, Action<IRoute>?).
Task RouteAsync(string url, Action<IRoute> handler, PageRouteOptions? options = null)
Parameters
url
stringA glob pattern, regex pattern or predicate receiving
to match while routing. When a baseURL
via the context options was provided and the passed URL is a path, it gets merged via thenew URL()
constructor.handler
Action<IRoute>handler function to route the request.
options
PageRouteOptionsCall options
Returns
Remarks
The handler will only be called for the first url if the response is a redirect.
RouteAsync(string, Action<IRoute>, PageRouteOptions?) will not intercept requests intercepted by Service
Worker. See this
issue. We recommend disabling Service Workers when using request interception by
setting Browser.newContext.serviceWorkers.newContext.serviceWorkers
to 'block'
.
RouteAsync(string, Action<IRoute>, PageRouteOptions?) will not intercept the first request of a popup page. Use RouteAsync(string, Action<IRoute>, BrowserContextRouteOptions?) instead.
Enabling routing disables http cache.
RouteAsync(string, Func<IRoute, Task>, PageRouteOptions?)
Task RouteAsync(string url, Func<IRoute, Task> handler, PageRouteOptions? options = null)
Parameters
url
stringhandler
Func<IRoute, Task>options
PageRouteOptions
Returns
RouteAsync(Regex, Action<IRoute>, PageRouteOptions?)
Routing provides the capability to modify network requests that are made by a page.
Once routing is enabled, every request matching the url pattern will stall unless it's continued, fulfilled or aborted.
**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 RouteAsync(string, Action<IRoute>, BrowserContextRouteOptions?)) when request matches both handlers.
To remove a route with its handler you can use UnrouteAsync(string, Action<IRoute>?).
Task RouteAsync(Regex url, Action<IRoute> handler, PageRouteOptions? options = null)
Parameters
url
RegexA glob pattern, regex pattern or predicate receiving
to match while routing. When a baseURL
via the context options was provided and the passed URL is a path, it gets merged via thenew URL()
constructor.handler
Action<IRoute>handler function to route the request.
options
PageRouteOptionsCall options
Returns
Remarks
The handler will only be called for the first url if the response is a redirect.
RouteAsync(string, Action<IRoute>, PageRouteOptions?) will not intercept requests intercepted by Service
Worker. See this
issue. We recommend disabling Service Workers when using request interception by
setting Browser.newContext.serviceWorkers.newContext.serviceWorkers
to 'block'
.
RouteAsync(string, Action<IRoute>, PageRouteOptions?) will not intercept the first request of a popup page. Use RouteAsync(string, Action<IRoute>, BrowserContextRouteOptions?) instead.
Enabling routing disables http cache.
RouteAsync(Regex, Func<IRoute, Task>, PageRouteOptions?)
Task RouteAsync(Regex url, Func<IRoute, Task> handler, PageRouteOptions? options = null)
Parameters
url
Regexhandler
Func<IRoute, Task>options
PageRouteOptions
Returns
RouteFromHARAsync(string, PageRouteFromHAROptions?)
If specified the network requests that are made in the page will be served from the HAR file. Read more about Replaying from HAR.
Playwright will not serve requests intercepted by Service Worker from the HAR file.
See this issue.
We recommend disabling Service Workers when using request interception by setting
Browser.newContext.serviceWorkers.newContext.serviceWorkers
to 'block'
.
Task RouteFromHARAsync(string har, PageRouteFromHAROptions? options = null)
Parameters
har
stringPath 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
PageRouteFromHAROptionsCall options
Returns
RunAndWaitForConsoleMessageAsync(Func<Task>, PageRunAndWaitForConsoleMessageOptions?)
Performs action and waits for a IConsoleMessage to be logged by in
the page. If predicate is provided, it passes IConsoleMessage value
into the predicate
function and waits for predicate(message)
to return
a truthy value. Will throw an error if the page is closed before the Console
event is fired.
Task<IConsoleMessage> RunAndWaitForConsoleMessageAsync(Func<Task> action, PageRunAndWaitForConsoleMessageOptions? options = null)
Parameters
action
Func<Task>Action that triggers the event.
options
PageRunAndWaitForConsoleMessageOptionsCall options
Returns
RunAndWaitForDownloadAsync(Func<Task>, PageRunAndWaitForDownloadOptions?)
Performs action and waits for a new IDownload. If predicate is provided,
it passes IDownload 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.
Task<IDownload> RunAndWaitForDownloadAsync(Func<Task> action, PageRunAndWaitForDownloadOptions? options = null)
Parameters
action
Func<Task>Action that triggers the event.
options
PageRunAndWaitForDownloadOptionsCall options
Returns
RunAndWaitForFileChooserAsync(Func<Task>, PageRunAndWaitForFileChooserOptions?)
Performs action and waits for a new IFileChooser to be created. If
predicate is provided, it passes IFileChooser 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.
Task<IFileChooser> RunAndWaitForFileChooserAsync(Func<Task> action, PageRunAndWaitForFileChooserOptions? options = null)
Parameters
action
Func<Task>Action that triggers the event.
options
PageRunAndWaitForFileChooserOptionsCall options
Returns
RunAndWaitForNavigationAsync(Func<Task>, PageRunAndWaitForNavigationOptions?)
**DEPRECATED** This method is inherently racy, please use WaitForURLAsync(string, PageWaitForURLOptions?) 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
[Obsolete]
Task<IResponse?> RunAndWaitForNavigationAsync(Func<Task> action, PageRunAndWaitForNavigationOptions? options = null)
Parameters
action
Func<Task>Action that triggers the event.
options
PageRunAndWaitForNavigationOptionsCall options
Returns
Remarks
Usage of the History API to change the URL is considered a navigation.
RunAndWaitForPopupAsync(Func<Task>, PageRunAndWaitForPopupOptions?)
Performs action and waits for a popup IPage. 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.
Task<IPage> RunAndWaitForPopupAsync(Func<Task> action, PageRunAndWaitForPopupOptions? options = null)
Parameters
action
Func<Task>Action that triggers the event.
options
PageRunAndWaitForPopupOptionsCall options
Returns
RunAndWaitForRequestAsync(Func<Task>, Func<IRequest, bool>, PageRunAndWaitForRequestOptions?)
Waits for the matching request and returns it. See waiting for event for more details about events.
**Usage**
// Waits for the next request with the specified url.
await page.RunAndWaitForRequestAsync(async () =>
{
await page.GetByText("trigger request").ClickAsync();
}, "http://example.com/resource");
// Alternative way with a predicate.
await page.RunAndWaitForRequestAsync(async () =>
{
await page.GetByText("trigger request").ClickAsync();
}, request => request.Url == "https://example.com" && request.Method == "GET");
Task<IRequest> RunAndWaitForRequestAsync(Func<Task> action, Func<IRequest, bool> urlOrPredicate, PageRunAndWaitForRequestOptions? options = null)
Parameters
action
Func<Task>Action that triggers the event.
urlOrPredicate
Func<IRequest, bool>Request URL string, regex or predicate receiving IRequest object. When a
baseURL
via the context options was provided and the passed URL is a path, it gets merged via thenew URL()
constructor.options
PageRunAndWaitForRequestOptionsCall options
Returns
RunAndWaitForRequestAsync(Func<Task>, string, PageRunAndWaitForRequestOptions?)
Waits for the matching request and returns it. See waiting for event for more details about events.
**Usage**
// Waits for the next request with the specified url.
await page.RunAndWaitForRequestAsync(async () =>
{
await page.GetByText("trigger request").ClickAsync();
}, "http://example.com/resource");
// Alternative way with a predicate.
await page.RunAndWaitForRequestAsync(async () =>
{
await page.GetByText("trigger request").ClickAsync();
}, request => request.Url == "https://example.com" && request.Method == "GET");
Task<IRequest> RunAndWaitForRequestAsync(Func<Task> action, string urlOrPredicate, PageRunAndWaitForRequestOptions? options = null)
Parameters
action
Func<Task>Action that triggers the event.
urlOrPredicate
stringRequest URL string, regex or predicate receiving IRequest object. When a
baseURL
via the context options was provided and the passed URL is a path, it gets merged via thenew URL()
constructor.options
PageRunAndWaitForRequestOptionsCall options
Returns
RunAndWaitForRequestAsync(Func<Task>, Regex, PageRunAndWaitForRequestOptions?)
Waits for the matching request and returns it. See waiting for event for more details about events.
**Usage**
// Waits for the next request with the specified url.
await page.RunAndWaitForRequestAsync(async () =>
{
await page.GetByText("trigger request").ClickAsync();
}, "http://example.com/resource");
// Alternative way with a predicate.
await page.RunAndWaitForRequestAsync(async () =>
{
await page.GetByText("trigger request").ClickAsync();
}, request => request.Url == "https://example.com" && request.Method == "GET");
Task<IRequest> RunAndWaitForRequestAsync(Func<Task> action, Regex urlOrPredicate, PageRunAndWaitForRequestOptions? options = null)
Parameters
action
Func<Task>Action that triggers the event.
urlOrPredicate
RegexRequest URL string, regex or predicate receiving IRequest object. When a
baseURL
via the context options was provided and the passed URL is a path, it gets merged via thenew URL()
constructor.options
PageRunAndWaitForRequestOptionsCall options
Returns
RunAndWaitForRequestFinishedAsync(Func<Task>, PageRunAndWaitForRequestFinishedOptions?)
Performs action and waits for a IRequest to finish loading. If predicate
is provided, it passes IRequest 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 RequestFinished event
is fired.
Task<IRequest> RunAndWaitForRequestFinishedAsync(Func<Task> action, PageRunAndWaitForRequestFinishedOptions? options = null)
Parameters
action
Func<Task>Action that triggers the event.
options
PageRunAndWaitForRequestFinishedOptionsCall options
Returns
RunAndWaitForResponseAsync(Func<Task>, Func<IResponse, bool>, PageRunAndWaitForResponseOptions?)
Returns the matched response. See waiting for event for more details about events.
**Usage**
// Waits for the next response with the specified url.
await page.RunAndWaitForResponseAsync(async () =>
{
await page.GetByText("trigger response").ClickAsync();
}, "http://example.com/resource");
// Alternative way with a predicate.
await page.RunAndWaitForResponseAsync(async () =>
{
await page.GetByText("trigger response").ClickAsync();
}, response => response.Url == "https://example.com" && response.Status == 200 && response.Request.Method == "GET");
Task<IResponse> RunAndWaitForResponseAsync(Func<Task> action, Func<IResponse, bool> urlOrPredicate, PageRunAndWaitForResponseOptions? options = null)
Parameters
action
Func<Task>Action that triggers the event.
urlOrPredicate
Func<IResponse, bool>Request URL string, regex or predicate receiving IResponse object. When a
baseURL
via the context options was provided and the passed URL is a path, it gets merged via thenew URL()
constructor.options
PageRunAndWaitForResponseOptionsCall options
Returns
RunAndWaitForResponseAsync(Func<Task>, string, PageRunAndWaitForResponseOptions?)
Returns the matched response. See waiting for event for more details about events.
**Usage**
// Waits for the next response with the specified url.
await page.RunAndWaitForResponseAsync(async () =>
{
await page.GetByText("trigger response").ClickAsync();
}, "http://example.com/resource");
// Alternative way with a predicate.
await page.RunAndWaitForResponseAsync(async () =>
{
await page.GetByText("trigger response").ClickAsync();
}, response => response.Url == "https://example.com" && response.Status == 200 && response.Request.Method == "GET");
Task<IResponse> RunAndWaitForResponseAsync(Func<Task> action, string urlOrPredicate, PageRunAndWaitForResponseOptions? options = null)
Parameters
action
Func<Task>Action that triggers the event.
urlOrPredicate
stringRequest URL string, regex or predicate receiving IResponse object. When a
baseURL
via the context options was provided and the passed URL is a path, it gets merged via thenew URL()
constructor.options
PageRunAndWaitForResponseOptionsCall options
Returns
RunAndWaitForResponseAsync(Func<Task>, Regex, PageRunAndWaitForResponseOptions?)
Returns the matched response. See waiting for event for more details about events.
**Usage**
// Waits for the next response with the specified url.
await page.RunAndWaitForResponseAsync(async () =>
{
await page.GetByText("trigger response").ClickAsync();
}, "http://example.com/resource");
// Alternative way with a predicate.
await page.RunAndWaitForResponseAsync(async () =>
{
await page.GetByText("trigger response").ClickAsync();
}, response => response.Url == "https://example.com" && response.Status == 200 && response.Request.Method == "GET");
Task<IResponse> RunAndWaitForResponseAsync(Func<Task> action, Regex urlOrPredicate, PageRunAndWaitForResponseOptions? options = null)
Parameters
action
Func<Task>Action that triggers the event.
urlOrPredicate
RegexRequest URL string, regex or predicate receiving IResponse object. When a
baseURL
via the context options was provided and the passed URL is a path, it gets merged via thenew URL()
constructor.options
PageRunAndWaitForResponseOptionsCall options
Returns
RunAndWaitForWebSocketAsync(Func<Task>, PageRunAndWaitForWebSocketOptions?)
Performs action and waits for a new IWebSocket. If predicate is provided,
it passes IWebSocket 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.
Task<IWebSocket> RunAndWaitForWebSocketAsync(Func<Task> action, PageRunAndWaitForWebSocketOptions? options = null)
Parameters
action
Func<Task>Action that triggers the event.
options
PageRunAndWaitForWebSocketOptionsCall options
Returns
RunAndWaitForWorkerAsync(Func<Task>, PageRunAndWaitForWorkerOptions?)
Performs action and waits for a new IWorker. If predicate is provided,
it passes IWorker 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.
Task<IWorker> RunAndWaitForWorkerAsync(Func<Task> action, PageRunAndWaitForWorkerOptions? options = null)
Parameters
action
Func<Task>Action that triggers the event.
options
PageRunAndWaitForWorkerOptionsCall options
Returns
ScreenshotAsync(PageScreenshotOptions?)
Returns the buffer with the captured screenshot.
Task<byte[]> ScreenshotAsync(PageScreenshotOptions? options = null)
Parameters
options
PageScreenshotOptionsCall options
Returns
SelectOptionAsync(string, IElementHandle, PageSelectOptionOptions?)
Use locator-based SelectOptionAsync(string, LocatorSelectOptionOptions?) 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" });
Task<IReadOnlyList<string>> SelectOptionAsync(string selector, IElementHandle values, PageSelectOptionOptions? options = null)
Parameters
selector
stringA selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
values
IElementHandleOptions 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
PageSelectOptionOptionsCall options
Returns
SelectOptionAsync(string, SelectOptionValue, PageSelectOptionOptions?)
Use locator-based SelectOptionAsync(string, LocatorSelectOptionOptions?) 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" });
Task<IReadOnlyList<string>> SelectOptionAsync(string selector, SelectOptionValue values, PageSelectOptionOptions? options = null)
Parameters
selector
stringA selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
values
SelectOptionValueOptions 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
PageSelectOptionOptionsCall options
Returns
SelectOptionAsync(string, IEnumerable<IElementHandle>, PageSelectOptionOptions?)
Use locator-based SelectOptionAsync(string, LocatorSelectOptionOptions?) 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" });
Task<IReadOnlyList<string>> SelectOptionAsync(string selector, IEnumerable<IElementHandle> values, PageSelectOptionOptions? options = null)
Parameters
selector
stringA selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
values
IEnumerable<IElementHandle>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
PageSelectOptionOptionsCall options
Returns
SelectOptionAsync(string, IEnumerable<SelectOptionValue>, PageSelectOptionOptions?)
Use locator-based SelectOptionAsync(string, LocatorSelectOptionOptions?) 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" });
Task<IReadOnlyList<string>> SelectOptionAsync(string selector, IEnumerable<SelectOptionValue> values, PageSelectOptionOptions? options = null)
Parameters
selector
stringA selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
values
IEnumerable<SelectOptionValue>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
PageSelectOptionOptionsCall options
Returns
SelectOptionAsync(string, IEnumerable<string>, PageSelectOptionOptions?)
Use locator-based SelectOptionAsync(string, LocatorSelectOptionOptions?) 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" });
Task<IReadOnlyList<string>> SelectOptionAsync(string selector, IEnumerable<string> values, PageSelectOptionOptions? options = null)
Parameters
selector
stringA selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
values
IEnumerable<string>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
PageSelectOptionOptionsCall options
Returns
SelectOptionAsync(string, string, PageSelectOptionOptions?)
Use locator-based SelectOptionAsync(string, LocatorSelectOptionOptions?) 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" });
Task<IReadOnlyList<string>> SelectOptionAsync(string selector, string values, PageSelectOptionOptions? options = null)
Parameters
selector
stringA selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
values
stringOptions 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
PageSelectOptionOptionsCall options
Returns
SetCheckedAsync(string, bool, PageSetCheckedOptions?)
Use locator-based SetCheckedAsync(bool, LocatorSetCheckedOptions?) instead. Read more about locators.
This method checks or unchecks an element matching selector
by
performing the following steps:
When all steps combined have not finished during the specified timeout
,
this method throws a TimeoutException. Passing zero timeout disables
this.
Task SetCheckedAsync(string selector, bool checkedState, PageSetCheckedOptions? options = null)
Parameters
selector
stringA selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
checkedState
boolWhether to check or uncheck the checkbox.
options
PageSetCheckedOptionsCall options
Returns
SetContentAsync(string, PageSetContentOptions?)
This method internally calls document.write(), inheriting all its specific characteristics and behaviors.
Task SetContentAsync(string html, PageSetContentOptions? options = null)
Parameters
html
stringHTML markup to assign to the page.
options
PageSetContentOptionsCall options
Returns
SetDefaultNavigationTimeout(float)
This setting will change the default maximum navigation time for the following methods and related shortcuts:
- GoBackAsync(PageGoBackOptions?)
- GoForwardAsync(PageGoForwardOptions?)
- GotoAsync(string, PageGotoOptions?)
- ReloadAsync(PageReloadOptions?)
- SetContentAsync(string, PageSetContentOptions?)
- RunAndWaitForNavigationAsync(Func<Task>, PageRunAndWaitForNavigationOptions?)
- WaitForURLAsync(string, PageWaitForURLOptions?)
void SetDefaultNavigationTimeout(float timeout)
Parameters
timeout
floatMaximum navigation time in milliseconds
Remarks
SetDefaultNavigationTimeout(float) takes priority over SetDefaultTimeout(float), SetDefaultTimeout(float) and SetDefaultNavigationTimeout(float).
SetDefaultTimeout(float)
This setting will change the default maximum time for all the methods accepting
timeout
option.
void SetDefaultTimeout(float timeout)
Parameters
timeout
floatMaximum time in milliseconds
Remarks
SetDefaultNavigationTimeout(float) takes priority over SetDefaultTimeout(float).
SetExtraHTTPHeadersAsync(IEnumerable<KeyValuePair<string, string>>)
The extra HTTP headers will be sent with every request the page initiates.
Task SetExtraHTTPHeadersAsync(IEnumerable<KeyValuePair<string, string>> headers)
Parameters
headers
IEnumerable<KeyValuePair<string, string>>An object containing additional HTTP headers to be sent with every request. All header values must be strings.
Returns
Remarks
SetExtraHTTPHeadersAsync(IEnumerable<KeyValuePair<string, string>>) does not guarantee the order of headers in the outgoing requests.
SetInputFilesAsync(string, FilePayload, PageSetInputFilesOptions?)
Use locator-based SetInputFilesAsync(string, LocatorSetInputFilesOptions?) 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.
Task SetInputFilesAsync(string selector, FilePayload files, PageSetInputFilesOptions? options = null)
Parameters
selector
stringA selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
files
FilePayloadoptions
PageSetInputFilesOptionsCall options
Returns
SetInputFilesAsync(string, IEnumerable<FilePayload>, PageSetInputFilesOptions?)
Use locator-based SetInputFilesAsync(string, LocatorSetInputFilesOptions?) 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.
Task SetInputFilesAsync(string selector, IEnumerable<FilePayload> files, PageSetInputFilesOptions? options = null)
Parameters
selector
stringA selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
files
IEnumerable<FilePayload>options
PageSetInputFilesOptionsCall options
Returns
SetInputFilesAsync(string, IEnumerable<string>, PageSetInputFilesOptions?)
Use locator-based SetInputFilesAsync(string, LocatorSetInputFilesOptions?) 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.
Task SetInputFilesAsync(string selector, IEnumerable<string> files, PageSetInputFilesOptions? options = null)
Parameters
selector
stringA selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
files
IEnumerable<string>options
PageSetInputFilesOptionsCall options
Returns
SetInputFilesAsync(string, string, PageSetInputFilesOptions?)
Use locator-based SetInputFilesAsync(string, LocatorSetInputFilesOptions?) 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.
Task SetInputFilesAsync(string selector, string files, PageSetInputFilesOptions? options = null)
Parameters
selector
stringA selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
files
stringoptions
PageSetInputFilesOptionsCall options
Returns
SetViewportSizeAsync(int, int)
In the case of multiple pages in a single browser, each page can have its own viewport size. However, NewContextAsync(BrowserNewContextOptions?) allows to set viewport size (and more) for all pages in the context at once.
SetViewportSizeAsync(int, int) 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. SetViewportSizeAsync(int, int) will also reset screen
size, use NewContextAsync(BrowserNewContextOptions?) 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");
Task SetViewportSizeAsync(int width, int height)
Parameters
Returns
TapAsync(string, PageTapOptions?)
Use locator-based TapAsync(LocatorTapOptions?) instead. Read more about locators.
This method taps an element matching selector
by performing the
following steps:
When all steps combined have not finished during the specified timeout
,
this method throws a TimeoutException. Passing zero timeout disables
this.
Task TapAsync(string selector, PageTapOptions? options = null)
Parameters
selector
stringA selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
options
PageTapOptionsCall options
Returns
Remarks
TapAsync(string, PageTapOptions?) the method will throw if hasTouch
option of the browser context is false.
TextContentAsync(string, PageTextContentOptions?)
Use locator-based TextContentAsync(LocatorTextContentOptions?) instead. Read more about locators.
Returns element.textContent
.
Task<string?> TextContentAsync(string selector, PageTextContentOptions? options = null)
Parameters
selector
stringA selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
options
PageTextContentOptionsCall options
Returns
TitleAsync()
Returns the page's title.
Task<string> TitleAsync()
Returns
TypeAsync(string, string, PageTypeOptions?)
**DEPRECATED** In most cases, you should use FillAsync(string, LocatorFillOptions?) instead. You only need to press keys one by one if there is special keyboard handling on the page - in this case use PressSequentiallyAsync(string, LocatorPressSequentiallyOptions?).
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 FillAsync(string, string, PageFillOptions?).
To press a special key, like Control
or ArrowDown
, use PressAsync(string, KeyboardPressOptions?).
**Usage**
[Obsolete]
Task TypeAsync(string selector, string text, PageTypeOptions? options = null)
Parameters
selector
stringA selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
text
stringA text to type into a focused element.
options
PageTypeOptionsCall options
Returns
UncheckAsync(string, PageUncheckOptions?)
Use locator-based UncheckAsync(LocatorUncheckOptions?) instead. Read more about locators.
This method unchecks an element matching selector
by performing
the following steps:
When all steps combined have not finished during the specified timeout
,
this method throws a TimeoutException. Passing zero timeout disables
this.
Task UncheckAsync(string selector, PageUncheckOptions? options = null)
Parameters
selector
stringA selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
options
PageUncheckOptionsCall options
Returns
UnrouteAllAsync(PageUnrouteAllOptions?)
Removes all routes created with RouteAsync(string, Action<IRoute>, PageRouteOptions?) and RouteFromHARAsync(string, PageRouteFromHAROptions?).
Task UnrouteAllAsync(PageUnrouteAllOptions? options = null)
Parameters
options
PageUnrouteAllOptionsCall options
Returns
UnrouteAsync(Func<string, bool>, Action<IRoute>?)
Removes a route created with RouteAsync(string, Action<IRoute>, PageRouteOptions?). When handler
is not specified, removes all routes for the url
.
Task UnrouteAsync(Func<string, bool> url, Action<IRoute>? handler = null)
Parameters
url
Func<string, bool>A glob pattern, regex pattern or predicate receiving
to match while routing. handler
Action<IRoute>Optional handler function to route the request.
Returns
UnrouteAsync(Func<string, bool>, Func<IRoute, Task>)
Task UnrouteAsync(Func<string, bool> url, Func<IRoute, Task> handler)
Parameters
Returns
UnrouteAsync(string, Action<IRoute>?)
Removes a route created with RouteAsync(string, Action<IRoute>, PageRouteOptions?). When handler
is not specified, removes all routes for the url
.
Task UnrouteAsync(string url, Action<IRoute>? handler = null)
Parameters
url
stringA glob pattern, regex pattern or predicate receiving
to match while routing. handler
Action<IRoute>Optional handler function to route the request.
Returns
UnrouteAsync(string, Func<IRoute, Task>)
Task UnrouteAsync(string url, Func<IRoute, Task> handler)
Parameters
Returns
UnrouteAsync(Regex, Action<IRoute>?)
Removes a route created with RouteAsync(string, Action<IRoute>, PageRouteOptions?). When handler
is not specified, removes all routes for the url
.
Task UnrouteAsync(Regex url, Action<IRoute>? handler = null)
Parameters
url
RegexA glob pattern, regex pattern or predicate receiving
to match while routing. handler
Action<IRoute>Optional handler function to route the request.
Returns
UnrouteAsync(Regex, Func<IRoute, Task>)
Task UnrouteAsync(Regex url, Func<IRoute, Task> handler)
Parameters
Returns
WaitForConsoleMessageAsync(PageWaitForConsoleMessageOptions?)
Performs action and waits for a IConsoleMessage to be logged by in
the page. If predicate is provided, it passes IConsoleMessage value
into the predicate
function and waits for predicate(message)
to return
a truthy value. Will throw an error if the page is closed before the Console
event is fired.
Task<IConsoleMessage> WaitForConsoleMessageAsync(PageWaitForConsoleMessageOptions? options = null)
Parameters
options
PageWaitForConsoleMessageOptionsCall options
Returns
WaitForDownloadAsync(PageWaitForDownloadOptions?)
Performs action and waits for a new IDownload. If predicate is provided,
it passes IDownload 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.
Task<IDownload> WaitForDownloadAsync(PageWaitForDownloadOptions? options = null)
Parameters
options
PageWaitForDownloadOptionsCall options
Returns
WaitForFileChooserAsync(PageWaitForFileChooserOptions?)
Performs action and waits for a new IFileChooser to be created. If
predicate is provided, it passes IFileChooser 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.
Task<IFileChooser> WaitForFileChooserAsync(PageWaitForFileChooserOptions? options = null)
Parameters
options
PageWaitForFileChooserOptionsCall options
Returns
WaitForFunctionAsync(string, object?, PageWaitForFunctionOptions?)
Returns when the expression
returns a truthy value. It resolves
to a JSHandle of the truthy value.
**Usage**
The WaitForFunctionAsync(string, object?, PageWaitForFunctionOptions?) 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 WaitForFunctionAsync(string, object?, PageWaitForFunctionOptions?) function:
var selector = ".foo";
await page.WaitForFunctionAsync("selector => !!document.querySelector(selector)", selector);
Task<IJSHandle> WaitForFunctionAsync(string expression, object? arg = null, PageWaitForFunctionOptions? options = null)
Parameters
expression
stringJavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the function is automatically invoked.
arg
objectOptional argument to pass to
expression
.options
PageWaitForFunctionOptionsCall options
Returns
WaitForLoadStateAsync(LoadState?, PageWaitForLoadStateOptions?)
Returns when the required load state has been reached.
This resolves when the page reaches a required load state, load
by default.
The navigation must have been committed when this method is called. If current document
has already reached the required state, resolves immediately.
**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.
Task WaitForLoadStateAsync(LoadState? state = null, PageWaitForLoadStateOptions? options = null)
Parameters
state
LoadState?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
PageWaitForLoadStateOptionsCall options
Returns
Remarks
Most of the time, this method is not needed because Playwright auto-waits before every action.
WaitForNavigationAsync(PageWaitForNavigationOptions?)
**DEPRECATED** This method is inherently racy, please use WaitForURLAsync(string, PageWaitForURLOptions?) 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
[Obsolete]
Task<IResponse?> WaitForNavigationAsync(PageWaitForNavigationOptions? options = null)
Parameters
options
PageWaitForNavigationOptionsCall options
Returns
Remarks
Usage of the History API to change the URL is considered a navigation.
WaitForPopupAsync(PageWaitForPopupOptions?)
Performs action and waits for a popup IPage. 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.
Task<IPage> WaitForPopupAsync(PageWaitForPopupOptions? options = null)
Parameters
options
PageWaitForPopupOptionsCall options
Returns
WaitForRequestAsync(Func<IRequest, bool>, PageWaitForRequestOptions?)
Waits for the matching request and returns it. See waiting for event for more details about events.
**Usage**
// Waits for the next request with the specified url.
await page.RunAndWaitForRequestAsync(async () =>
{
await page.GetByText("trigger request").ClickAsync();
}, "http://example.com/resource");
// Alternative way with a predicate.
await page.RunAndWaitForRequestAsync(async () =>
{
await page.GetByText("trigger request").ClickAsync();
}, request => request.Url == "https://example.com" && request.Method == "GET");
Task<IRequest> WaitForRequestAsync(Func<IRequest, bool> urlOrPredicate, PageWaitForRequestOptions? options = null)
Parameters
urlOrPredicate
Func<IRequest, bool>Request URL string, regex or predicate receiving IRequest object. When a
baseURL
via the context options was provided and the passed URL is a path, it gets merged via thenew URL()
constructor.options
PageWaitForRequestOptionsCall options
Returns
WaitForRequestAsync(string, PageWaitForRequestOptions?)
Waits for the matching request and returns it. See waiting for event for more details about events.
**Usage**
// Waits for the next request with the specified url.
await page.RunAndWaitForRequestAsync(async () =>
{
await page.GetByText("trigger request").ClickAsync();
}, "http://example.com/resource");
// Alternative way with a predicate.
await page.RunAndWaitForRequestAsync(async () =>
{
await page.GetByText("trigger request").ClickAsync();
}, request => request.Url == "https://example.com" && request.Method == "GET");
Task<IRequest> WaitForRequestAsync(string urlOrPredicate, PageWaitForRequestOptions? options = null)
Parameters
urlOrPredicate
stringRequest URL string, regex or predicate receiving IRequest object. When a
baseURL
via the context options was provided and the passed URL is a path, it gets merged via thenew URL()
constructor.options
PageWaitForRequestOptionsCall options
Returns
WaitForRequestAsync(Regex, PageWaitForRequestOptions?)
Waits for the matching request and returns it. See waiting for event for more details about events.
**Usage**
// Waits for the next request with the specified url.
await page.RunAndWaitForRequestAsync(async () =>
{
await page.GetByText("trigger request").ClickAsync();
}, "http://example.com/resource");
// Alternative way with a predicate.
await page.RunAndWaitForRequestAsync(async () =>
{
await page.GetByText("trigger request").ClickAsync();
}, request => request.Url == "https://example.com" && request.Method == "GET");
Task<IRequest> WaitForRequestAsync(Regex urlOrPredicate, PageWaitForRequestOptions? options = null)
Parameters
urlOrPredicate
RegexRequest URL string, regex or predicate receiving IRequest object. When a
baseURL
via the context options was provided and the passed URL is a path, it gets merged via thenew URL()
constructor.options
PageWaitForRequestOptionsCall options
Returns
WaitForRequestFinishedAsync(PageWaitForRequestFinishedOptions?)
Performs action and waits for a IRequest to finish loading. If predicate
is provided, it passes IRequest 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 RequestFinished event
is fired.
Task<IRequest> WaitForRequestFinishedAsync(PageWaitForRequestFinishedOptions? options = null)
Parameters
options
PageWaitForRequestFinishedOptionsCall options
Returns
WaitForResponseAsync(Func<IResponse, bool>, PageWaitForResponseOptions?)
Returns the matched response. See waiting for event for more details about events.
**Usage**
// Waits for the next response with the specified url.
await page.RunAndWaitForResponseAsync(async () =>
{
await page.GetByText("trigger response").ClickAsync();
}, "http://example.com/resource");
// Alternative way with a predicate.
await page.RunAndWaitForResponseAsync(async () =>
{
await page.GetByText("trigger response").ClickAsync();
}, response => response.Url == "https://example.com" && response.Status == 200 && response.Request.Method == "GET");
Task<IResponse> WaitForResponseAsync(Func<IResponse, bool> urlOrPredicate, PageWaitForResponseOptions? options = null)
Parameters
urlOrPredicate
Func<IResponse, bool>Request URL string, regex or predicate receiving IResponse object. When a
baseURL
via the context options was provided and the passed URL is a path, it gets merged via thenew URL()
constructor.options
PageWaitForResponseOptionsCall options
Returns
WaitForResponseAsync(string, PageWaitForResponseOptions?)
Returns the matched response. See waiting for event for more details about events.
**Usage**
// Waits for the next response with the specified url.
await page.RunAndWaitForResponseAsync(async () =>
{
await page.GetByText("trigger response").ClickAsync();
}, "http://example.com/resource");
// Alternative way with a predicate.
await page.RunAndWaitForResponseAsync(async () =>
{
await page.GetByText("trigger response").ClickAsync();
}, response => response.Url == "https://example.com" && response.Status == 200 && response.Request.Method == "GET");
Task<IResponse> WaitForResponseAsync(string urlOrPredicate, PageWaitForResponseOptions? options = null)
Parameters
urlOrPredicate
stringRequest URL string, regex or predicate receiving IResponse object. When a
baseURL
via the context options was provided and the passed URL is a path, it gets merged via thenew URL()
constructor.options
PageWaitForResponseOptionsCall options
Returns
WaitForResponseAsync(Regex, PageWaitForResponseOptions?)
Returns the matched response. See waiting for event for more details about events.
**Usage**
// Waits for the next response with the specified url.
await page.RunAndWaitForResponseAsync(async () =>
{
await page.GetByText("trigger response").ClickAsync();
}, "http://example.com/resource");
// Alternative way with a predicate.
await page.RunAndWaitForResponseAsync(async () =>
{
await page.GetByText("trigger response").ClickAsync();
}, response => response.Url == "https://example.com" && response.Status == 200 && response.Request.Method == "GET");
Task<IResponse> WaitForResponseAsync(Regex urlOrPredicate, PageWaitForResponseOptions? options = null)
Parameters
urlOrPredicate
RegexRequest URL string, regex or predicate receiving IResponse object. When a
baseURL
via the context options was provided and the passed URL is a path, it gets merged via thenew URL()
constructor.options
PageWaitForResponseOptionsCall options
Returns
WaitForSelectorAsync(string, PageWaitForSelectorOptions?)
Use web assertions that assert visibility or a locator-based WaitForAsync(LocatorWaitForOptions?) instead. Read more about locators.
Returns when element specified by selector satisfies state
option.
Returns null
if waiting for hidden
or detached
.
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();
}
}
Task<IElementHandle?> WaitForSelectorAsync(string selector, PageWaitForSelectorOptions? options = null)
Parameters
selector
stringA selector to query for.
options
PageWaitForSelectorOptionsCall options
Returns
Remarks
Playwright automatically waits for element to be ready before performing an action. Using ILocator objects and web-first assertions makes the code wait-for-selector-free.
WaitForTimeoutAsync(float)
Never wait for timeout in production. Tests that wait for time are inherently flaky. Use ILocator 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);
Task WaitForTimeoutAsync(float timeout)
Parameters
timeout
floatA timeout to wait for
Returns
WaitForURLAsync(Func<string, bool>, PageWaitForURLOptions?)
Waits for the main frame to navigate to the given URL.
**Usage**
await page.ClickAsync("a.delayed-navigation"); // clicking the link will indirectly cause a navigation
await page.WaitForURLAsync("**/target.html");
Task WaitForURLAsync(Func<string, bool> url, PageWaitForURLOptions? options = null)
Parameters
url
Func<string, bool>A glob pattern, regex pattern or predicate receiving
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
PageWaitForURLOptionsCall options
Returns
WaitForURLAsync(string, PageWaitForURLOptions?)
Waits for the main frame to navigate to the given URL.
**Usage**
await page.ClickAsync("a.delayed-navigation"); // clicking the link will indirectly cause a navigation
await page.WaitForURLAsync("**/target.html");
Task WaitForURLAsync(string url, PageWaitForURLOptions? options = null)
Parameters
url
stringA glob pattern, regex pattern or predicate receiving
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
PageWaitForURLOptionsCall options
Returns
WaitForURLAsync(Regex, PageWaitForURLOptions?)
Waits for the main frame to navigate to the given URL.
**Usage**
await page.ClickAsync("a.delayed-navigation"); // clicking the link will indirectly cause a navigation
await page.WaitForURLAsync("**/target.html");
Task WaitForURLAsync(Regex url, PageWaitForURLOptions? options = null)
Parameters
url
RegexA glob pattern, regex pattern or predicate receiving
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
PageWaitForURLOptionsCall options
Returns
WaitForWebSocketAsync(PageWaitForWebSocketOptions?)
Performs action and waits for a new IWebSocket. If predicate is provided,
it passes IWebSocket 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.
Task<IWebSocket> WaitForWebSocketAsync(PageWaitForWebSocketOptions? options = null)
Parameters
options
PageWaitForWebSocketOptionsCall options
Returns
WaitForWorkerAsync(PageWaitForWorkerOptions?)
Performs action and waits for a new IWorker. If predicate is provided,
it passes IWorker 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.
Task<IWorker> WaitForWorkerAsync(PageWaitForWorkerOptions? options = null)
Parameters
options
PageWaitForWorkerOptionsCall options
Returns
Events
Close
Emitted when the page closes.
event EventHandler<IPage> Close
Event Type
Console
Emitted when JavaScript within the page calls one of console API methods, e.g. console.log
or console.dir
.
The arguments passed into console.log
are available on the IConsoleMessage
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 EventHandler<IConsoleMessage> Console
Event Type
Crash
Emitted when the page crashes. Browser pages might crash if they try to allocate too much memory. When the page crashes, ongoing and subsequent operations will throw.
The most common way to deal with crashes is to catch an exception:
try {
// Crash might happen during a click.
await page.ClickAsync("button");
// Or while waiting for an event.
await page.WaitForPopup();
} catch (PlaywrightException e) {
// When the page crashes, exception message contains "crash".
}
event EventHandler<IPage> Crash
Event Type
DOMContentLoaded
Emitted when the JavaScript DOMContentLoaded
event is dispatched.
event EventHandler<IPage> DOMContentLoaded
Event Type
Dialog
Emitted when a JavaScript dialog appears, such as alert
, prompt
, confirm
or beforeunload
. Listener **must** either AcceptAsync(string?)
or DismissAsync() the dialog - otherwise the page will freeze
waiting for the dialog, and actions like click will never finish.
**Usage**
page.RequestFailed += (_, request) =>
{
Console.WriteLine(request.Url + " " + request.Failure);
};
event EventHandler<IDialog> Dialog
Event Type
Remarks
Download
Emitted when attachment download started. User can access basic file operations on downloaded content via the passed IDownload instance.
event EventHandler<IDownload> Download
Event Type
FileChooser
Emitted when a file chooser is supposed to appear, such as after clicking the <input
type=file>
. Playwright can respond to it via setting the input files using
SetFilesAsync(string, FileChooserSetFilesOptions?) that can be uploaded after that.
page.FileChooser += (_, fileChooser) =>
{
fileChooser.SetFilesAsync(@"C:\temp\myfile.pdf");
};
event EventHandler<IFileChooser> FileChooser
Event Type
FrameAttached
Emitted when a frame is attached.
event EventHandler<IFrame> FrameAttached
Event Type
FrameDetached
Emitted when a frame is detached.
event EventHandler<IFrame> FrameDetached
Event Type
FrameNavigated
Emitted when a frame is navigated to a new url.
event EventHandler<IFrame> FrameNavigated
Event Type
Load
Emitted when the JavaScript load
event is dispatched.
event EventHandler<IPage> Load
Event Type
PageError
Emitted when an uncaught exception happens within the page.
// Log all uncaught errors to the terminal
page.PageError += (_, exception) =>
{
Console.WriteLine("Uncaught exception: " + exception);
};
event EventHandler<string> PageError
Event Type
Popup
Emitted when the page opens a new tab or window. This event is emitted in addition to the 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 RouteAsync(string, Action<IRoute>, BrowserContextRouteOptions?) and Request
respectively instead of similar methods on the IPage.
var popup = await page.RunAndWaitForPopupAsync(async () =>
{
await page.GetByText("open the popup").ClickAsync();
});
Console.WriteLine(await popup.EvaluateAsync<string>("location.href"));
event EventHandler<IPage> Popup
Event Type
Remarks
Use WaitForLoadStateAsync(LoadState?, PageWaitForLoadStateOptions?) to wait until the page gets to a particular state (you should not need it in most cases).
Request
Emitted when a page issues a request. The
event EventHandler<IRequest> Request
Event Type
RequestFailed
Emitted when a request fails, for example by timing out.
event EventHandler<IRequest> RequestFailed
Event Type
Remarks
HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request will complete with RequestFinished event and not with RequestFailed. 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.
RequestFinished
Emitted when a request finishes successfully after downloading the response body.
For a successful response, the sequence of events is request
, response
and requestfinished
.
event EventHandler<IRequest> RequestFinished
Event Type
Response
Emitted when request
, response
and requestfinished
.
event EventHandler<IResponse> Response
Event Type
WebSocket
Emitted when IWebSocket request is sent.
event EventHandler<IWebSocket> WebSocket
Event Type
Worker
Emitted when a dedicated WebWorker is spawned by the page.
event EventHandler<IWorker> Worker