Namespace Microsoft.Playwright
Classes
- BrowserType
Contains the browser types names.
- DialogType
Dialog type.
- RequestAbortErrorCode
Abort error codes.
- ViewportSize
View port data.
Interfaces
- IAPIRequest
Exposes API that can be used for the Web API testing. This class is used for creating IAPIRequestContext instance which in turn can be used for sending web requests. An instance of this class can be obtained via APIRequest. For more information see IAPIRequestContext.
- IAPIRequestContext
This API is used for the Web API testing. You can use it to trigger API endpoints, configure micro-services, prepare environment or the service to your e2e test.
Each Playwright browser context has associated with it IAPIRequestContext instance which shares cookie storage with the browser context and can be accessed via APIRequest or APIRequest. It is also possible to create a new APIRequestContext instance manually by calling NewContextAsync(APIRequestNewContextOptions?).
**Cookie management**
IAPIRequestContext returned by APIRequest and APIRequest shares cookie storage with the corresponding IBrowserContext. Each API request will have
Cookie
header populated with the values from the browser context. If the API response containsSet-Cookie
header it will automatically update IBrowserContext cookies and requests made from the page will pick them up. This means that if you log in using this API, your e2e test will be logged in and vice versa.If you want API requests to not interfere with the browser cookies you should create a new IAPIRequestContext by calling NewContextAsync(APIRequestNewContextOptions?). Such
APIRequestContext
object will have its own isolated cookie storage.
- IAPIResponse
IAPIResponse class represents responses returned by GetAsync(string, APIRequestContextOptions?) and similar methods.
- IAPIResponseAssertions
The IAPIResponseAssertions class provides assertion methods that can be used to make assertions about the IAPIResponse in the tests.
- IAccessibility
**DEPRECATED** This class is deprecated. Please use other libraries such as Axe if you need to test page accessibility. See our Node.js guide for integration with Axe.
The Accessibility class provides methods for inspecting Chromium's accessibility tree. The accessibility tree is used by assistive technology such as screen readers or switches.
Accessibility is a very platform-specific thing. On different platforms, there are different screen readers that might have wildly different output.
Rendering engines of Chromium, Firefox and WebKit have a concept of "accessibility tree", which is then translated into different platform-specific APIs. Accessibility namespace gives access to this Accessibility Tree.
Most of the accessibility tree gets filtered out when converting from internal browser AX Tree to Platform-specific AX-Tree or by assistive technologies themselves. By default, Playwright tries to approximate this filtering, exposing only the "interesting" nodes of the tree.
- IBrowser
A Browser is created via LaunchAsync(BrowserTypeLaunchOptions?). An example of using a IBrowser to create a IPage:
using Microsoft.Playwright;
using var playwright = await Playwright.CreateAsync(); var firefox = playwright.Firefox; var browser = await firefox.LaunchAsync(new() { Headless = false }); var page = await browser.NewPageAsync(); await page.GotoAsync("https://www.bing.com"); await browser.CloseAsync();
- IBrowserContext
BrowserContexts provide a way to operate multiple independent browser sessions.
If a page opens another page, e.g. with a
window.open
call, the popup will belong to the parent page's browser context.Playwright allows creating "incognito" browser contexts with NewContextAsync(BrowserNewContextOptions?) method. "Incognito" browser contexts don't write any browsing data to disk.
using var playwright = await Playwright.CreateAsync(); var browser = await playwright.Firefox.LaunchAsync(new() { Headless = false }); // Create a new incognito browser context var context = await browser.NewContextAsync(); // Create a new page inside context. var page = await context.NewPageAsync(); await page.GotoAsync("https://bing.com"); // Dispose context once it is no longer needed. await context.CloseAsync();
- IBrowserType
BrowserType provides methods to launch a specific browser instance or connect to an existing one. The following is a typical example of using Playwright to drive automation:
using Microsoft.Playwright; using System.Threading.Tasks;
class BrowserTypeExamples { public static async Task Run() { using var playwright = await Playwright.CreateAsync(); var chromium = playwright.Chromium; var browser = await chromium.LaunchAsync(); var page = await browser.NewPageAsync(); await page.GotoAsync("https://www.bing.com"); // other actions await browser.CloseAsync(); } }
- ICDPSession
The
CDPSession
instances are used to talk raw Chrome Devtools Protocol:- protocol methods can be called with
session.send
method. - protocol events can be subscribed to with
session.on
method.
Useful links:
- Documentation on DevTools Protocol can be found here: DevTools Protocol Viewer.
- Getting Started with DevTools Protocol: https://github.com/aslushnikov/getting-started-with-cdp/blob/master/README.md
var client = await Page.Context.NewCDPSessionAsync(Page); await client.SendAsync("Runtime.enable"); client.Event("Animation.animationCreated").OnEvent += (_, _) => Console.WriteLine("Animation created!"); var response = await client.SendAsync("Animation.getPlaybackRate"); var playbackRate = response.Value.GetProperty("playbackRate").GetDouble(); Console.WriteLine("playback rate is " + playbackRate); await client.SendAsync("Animation.setPlaybackRate", new() { { "playbackRate", playbackRate / 2 } });
- protocol methods can be called with
- ICDPSessionEvent
ICDPSessionEvent objects are returned by page via the Event(string) method.
Each object represents a named event and allows handling of the event when it is raised.
- IClock
Accurately simulating time-dependent behavior is essential for verifying the correctness of applications. Learn more about clock emulation.
Note that clock is installed for the entire IBrowserContext, so the time in all the pages and iframes is controlled by the same clock.
- IConsoleMessage
IConsoleMessage objects are dispatched by page via the Console event. For each console message logged in the page there will be corresponding event in the Playwright context.
// Listen for all console messages and print them to the standard output. page.Console += (_, msg) => Console.WriteLine(msg.Text);
// Listen for all console messages and print errors to the standard output. page.Console += (_, msg) => { if ("error".Equals(msg.Type)) Console.WriteLine("Error text: " + msg.Text); };
// Get the next console message var waitForMessageTask = page.WaitForConsoleMessageAsync(); await page.EvaluateAsync("console.log('hello', 42, { foo: 'bar' });"); var message = await waitForMessageTask; // Deconstruct console.log arguments await message.Args.ElementAt(0).JsonValueAsync<string>(); // hello await message.Args.ElementAt(1).JsonValueAsync<int>(); // 42
- IDialog
IDialog objects are dispatched by page via the Dialog event.
An example of using
Dialog
class:using Microsoft.Playwright; using System.Threading.Tasks;
class DialogExample { public static async Task Run() { using var playwright = await Playwright.CreateAsync(); await using var browser = await playwright.Chromium.LaunchAsync(); var page = await browser.NewPageAsync();
page.Dialog += async (_, dialog) => { System.Console.WriteLine(dialog.Message); await dialog.DismissAsync(); }; await page.EvaluateAsync("alert('1');"); }
}
- IDownload
IDownload objects are dispatched by page via the Download event.
All the downloaded files belonging to the browser context are deleted when the browser context is closed.
Download event is emitted once the download starts. Download path becomes available once download completes.
// Start the task of waiting for the download before clicking var waitForDownloadTask = page.WaitForDownloadAsync(); await page.GetByText("Download file").ClickAsync(); var download = await waitForDownloadTask;
// Wait for the download process to complete and save the downloaded file somewhere await download.SaveAsAsync("/path/to/save/at/" + download.SuggestedFilename);
- IElementHandle
ElementHandle represents an in-page DOM element. ElementHandles can be created with the QuerySelectorAsync(string, PageQuerySelectorOptions?) method.
var handle = await page.QuerySelectorAsync("a"); await handle.ClickAsync();
ElementHandle prevents DOM element from garbage collection unless the handle is disposed with
. ElementHandles are auto-disposed when their origin frame gets navigated. ElementHandle instances can be used as an argument in EvalOnSelectorAsync(string, string, object?) and EvaluateAsync(string, object?) methods.
The difference between the ILocator and ElementHandle is that the ElementHandle points to a particular element, while ILocator captures the logic of how to retrieve an element.
In the example below, handle points to a particular DOM element on page. If that element changes text or is used by React to render an entirely different component, handle is still pointing to that very DOM element. This can lead to unexpected behaviors.
var handle = await page.QuerySelectorAsync("text=Submit"); await handle.HoverAsync(); await handle.ClickAsync();
With the locator, every time the
element
is used, up-to-date DOM element is located in the page using the selector. So in the snippet below, underlying DOM element is going to be located twice.var locator = page.GetByText("Submit"); await locator.HoverAsync(); await locator.ClickAsync();
- IFileChooser
IFileChooser objects are dispatched by the page in the FileChooser event.
var fileChooser = await page.RunAndWaitForFileChooserAsync(async () => { await page.GetByText("Upload file").ClickAsync(); }); await fileChooser.SetFilesAsync("temp.txt");
- IFormData
The IFormData is used create form data that is sent via IAPIRequestContext.
- IFrame
At every point of time, page exposes its current frame tree via the MainFrame and ChildFrames methods.
IFrame object's lifecycle is controlled by three events, dispatched on the page object:
- FrameAttached - fired when the frame gets attached to the page. A Frame can be attached to the page only once.
- FrameNavigated - fired when the frame commits navigation to a different URL.
- FrameDetached - fired when the frame gets detached from the page. A Frame can be detached from the page only once.
An example of dumping frame tree:
using Microsoft.Playwright; using System; using System.Threading.Tasks;
class FrameExamples { public static async Task Main() { using var playwright = await Playwright.CreateAsync(); await using var browser = await playwright.Firefox.LaunchAsync(); var page = await browser.NewPageAsync();
await page.GotoAsync("https://www.bing.com"); DumpFrameTree(page.MainFrame, string.Empty); } private static void DumpFrameTree(IFrame frame, string indent) { Console.WriteLine($"{indent}{frame.Url}"); foreach (var child in frame.ChildFrames) DumpFrameTree(child, indent + " "); }
}
- IFrameLocator
FrameLocator represents a view to the
iframe
on the page. It captures the logic sufficient to retrieve theiframe
and locate elements in that iframe. FrameLocator can be created with either FrameLocator(string) or FrameLocator(string) method.var locator = page.FrameLocator("#my-frame").GetByText("Submit"); await locator.ClickAsync();
**Strictness**
Frame locators are strict. This means that all operations on frame locators will throw if more than one element matches a given selector.
// Throws if there are several frames in DOM: await page.FrameLocator(".result-frame").GetByRole(AriaRole.Button).ClickAsync();
// Works because we explicitly tell locator to pick the first frame: await page.FrameLocator(".result-frame").First.getByRole(AriaRole.Button).ClickAsync();
**Converting Locator to FrameLocator**
If you have a ILocator object pointing to an
iframe
it can be converted to IFrameLocator using ContentFrame.**Converting FrameLocator to Locator**
If you have a IFrameLocator object it can be converted to ILocator pointing to the same
iframe
using Owner.
- IJSHandle
JSHandle represents an in-page JavaScript object. JSHandles can be created with the EvaluateHandleAsync(string, object?) method.
var windowHandle = await page.EvaluateHandleAsync("() => window");
JSHandle prevents the referenced JavaScript object being garbage collected unless the handle is exposed with
. JSHandles are auto-disposed when their origin frame gets navigated or the parent context gets destroyed. JSHandle instances can be used as an argument in EvalOnSelectorAsync(string, string, object?), EvaluateAsync(string, object?) and EvaluateHandleAsync(string, object?) methods.
- IKeyboard
Keyboard provides an api for managing a virtual keyboard. The high level api is TypeAsync(string, KeyboardTypeOptions?), which takes raw characters and generates proper
keydown
,keypress
/input
, andkeyup
events on your page.For finer control, you can use DownAsync(string), UpAsync(string), and InsertTextAsync(string) to manually fire events as if they were generated from a real keyboard.
An example of holding down
Shift
in order to select and delete some text:await page.Keyboard.TypeAsync("Hello World!"); await page.Keyboard.PressAsync("ArrowLeft");
await page.Keyboard.DownAsync("Shift"); for (int i = 0; i < " World".Length; i++) await page.Keyboard.PressAsync("ArrowLeft");
await page.Keyboard.UpAsync("Shift");
await page.Keyboard.PressAsync("Backspace"); // Result text will end up saying "Hello!"
An example of pressing uppercase
A
await page.Keyboard.PressAsync("Shift+KeyA"); // or await page.Keyboard.PressAsync("Shift+A");
An example to trigger select-all with the keyboard
// on Windows and Linux await page.Keyboard.PressAsync("Control+A"); // on macOS await page.Keyboard.PressAsync("Meta+A");
- ILocator
Locators are the central piece of Playwright's auto-waiting and retry-ability. In a nutshell, locators represent a way to find element(s) on the page at any moment. A locator can be created with the Locator(string, PageLocatorOptions?) method.
- ILocatorAssertions
The ILocatorAssertions class provides assertion methods that can be used to make assertions about the ILocator state in the tests.
using Microsoft.Playwright; using Microsoft.Playwright.MSTest;
namespace PlaywrightTests;
[TestClass] public class ExampleTests : PageTest { [TestMethod] public async Task StatusBecomesSubmitted() { // ... await Page.GetByRole(AriaRole.Button, new() { Name = "Sign In" }).ClickAsync(); await Expect(Page.Locator(".status")).ToHaveTextAsync("Submitted"); } }
- IMouse
The Mouse class operates in main-frame CSS pixels relative to the top-left corner of the viewport.
Every
page
object has its own Mouse, accessible with Mouse.await Page.Mouse.MoveAsync(0, 0); await Page.Mouse.DownAsync(); await Page.Mouse.MoveAsync(0, 100); await Page.Mouse.MoveAsync(100, 100); await Page.Mouse.MoveAsync(100, 0); await Page.Mouse.MoveAsync(0, 0); await Page.Mouse.UpAsync();
- IPage
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 ason
,once
orremoveListener
.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;
- IPageAssertions
The IPageAssertions class provides assertion methods that can be used to make assertions about the IPage state in the tests.
using System.Text.RegularExpressions; using Microsoft.Playwright; using Microsoft.Playwright.MSTest;
namespace PlaywrightTests;
[TestClass] public class ExampleTests : PageTest { [TestMethod] public async Task NavigatetoLoginPage() { await Page.GetByRole(AriaRole.Button, new() { Name = "Sign In" }).ClickAsync(); await Expect(Page).ToHaveURLAsync(new Regex(".*/login")); } }
- IPlaywright
Playwright module provides a method to launch a browser instance. The following is a typical example of using Playwright to drive automation:
using Microsoft.Playwright; using System.Threading.Tasks;
class PlaywrightExample { public static async Task Main() { using var playwright = await Playwright.CreateAsync(); await using var browser = await playwright.Chromium.LaunchAsync(); var page = await browser.NewPageAsync();
await page.GotoAsync("https://www.microsoft.com"); // other actions... }
}
- IPlaywrightAssertions
Playwright gives you Web-First Assertions with convenience methods for creating assertions that will wait and retry until the expected condition is met.
Consider the following example:
using Microsoft.Playwright; using Microsoft.Playwright.MSTest;
namespace PlaywrightTests;
[TestClass] public class ExampleTests : PageTest { [TestMethod] public async Task StatusBecomesSubmitted() { await Page.GetByRole(AriaRole.Button, new() { Name = "Submit" }).ClickAsync(); await Expect(Page.Locator(".status")).ToHaveTextAsync("Submitted"); } }
Playwright will be re-testing the node with the selector
.status
until fetched Node has the"Submitted"
text. It will be re-fetching the node and checking it over and over, until the condition is met or until the timeout is reached. You can pass this timeout as an option.By default, the timeout for assertions is set to 5 seconds.
- IRequest
Whenever the page sends a request for a network resource the following sequence of events are emitted by IPage:
- Request emitted when the request is issued by the page.
- Response emitted when/if the response status and headers are received for the request.
- RequestFinished emitted when the response body is downloaded and the request is complete.
If request fails at some point, then instead of
'requestfinished'
event (and possibly instead of 'response' event), the RequestFailed event is emitted.If request gets a 'redirect' response, the request is successfully finished with the
requestfinished
event, and a new request is issued to a redirected url.
- IRoute
Whenever a network route is set up with RouteAsync(string, Action<IRoute>, PageRouteOptions?) or RouteAsync(string, Action<IRoute>, BrowserContextRouteOptions?), the
Route
object allows to handle the route.Learn more about networking.
- ISelectors
Selectors can be used to install custom selector engines. See extensibility for more information.
- ITouchscreen
The Touchscreen class operates in main-frame CSS pixels relative to the top-left corner of the viewport. Methods on the touchscreen can only be used in browser contexts that have been initialized with
hasTouch
set to true.
- ITracing
API for collecting and saving Playwright traces. Playwright traces can be opened in Trace Viewer after Playwright script runs.
Start recording a trace before performing actions. At the end, stop tracing and save it to a file.
using var playwright = await Playwright.CreateAsync(); var browser = await playwright.Chromium.LaunchAsync(); await using var context = await browser.NewContextAsync(); await context.Tracing.StartAsync(new() { Screenshots = true, Snapshots = true }); var page = await context.NewPageAsync(); await page.GotoAsync("https://playwright.dev"); await context.Tracing.StopAsync(new() { Path = "trace.zip" });
- IVideo
When browser context is created with the
recordVideo
option, each page has a video object associated with it.Console.WriteLine(await page.Video.GetPathAsync());
- IWebError
IWebError class represents an unhandled exception thrown in the page. It is dispatched via the WebError event.
// Log all uncaught errors to the terminal context.WebError += (_, webError) => { Console.WriteLine("Uncaught exception: " + webError.Error); };
- IWebSocket
The IWebSocket class represents websocket connections in the page.
- IWebSocketFrame
The IWebSocketFrame class represents frames sent over IWebSocket connections in the page. Frame payload is returned by either Text or Binary method depending on the its type.
- IWorker
The Worker class represents a WebWorker.
worker
event is emitted on the page object to signal a worker creation.close
event is emitted on the worker object when the worker is gone.page.Worker += (_, worker) => { Console.WriteLine($"Worker created: {worker.Url}"); worker.Close += (_, _) => Console.WriteLine($"Worker closed {worker.Url}"); };
Console.WriteLine("Current Workers:"); foreach(var pageWorker in page.Workers) { Console.WriteLine($"\tWorker: {pageWorker.Url}"); }