### Open with config file Source: https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/skills/playwright-cli/SKILL.md Use `--config` to start with a configuration file. This example uses `my-config.json`. ```bash # Start with config file playwright-cli open --config=my-config.json ``` -------------------------------- ### Quick start with playwright-cli Source: https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/skills/playwright-cli/SKILL.md A basic workflow to open a browser, navigate, interact, take a screenshot, and close. Use this to get started quickly. ```bash # open new browser playwright-cli open # navigate to a page playwright-cli goto https://playwright.dev # interact with the page using refs from the snapshot playwright-cli click e15 playwright-cli type "page.click" playwright-cli press Enter # take a screenshot (rarely used, as snapshot is more common) playwright-cli screenshot # close the browser playwright-cli close ``` -------------------------------- ### Install Firefox beta and run BiDi tests with BIDI_FFPATH Source: https://github.com/microsoft/playwright/blob/main/tests/bidi/README.md Installs the Firefox beta channel in the project root and executes the BiDi test suite against the installed custom binary path. ```sh npx -y @puppeteer/browsers install firefox@beta ``` ```sh BIDI_FFPATH='/Users/myself/playwright/firefox/mac_arm-beta_138.0b5/Firefox.app/Contents/MacOS/firefox' npm run biditest -- --project='moz-firefox-*' ``` -------------------------------- ### Setup and teardown with autouse fixtures in test_example.py Source: https://github.com/microsoft/playwright/blob/main/docs/src/writing-tests-python.md Defines a function-scoped autouse fixture that runs setup before each test and teardown after each test. ```python import pytest from playwright.sync_api import Page, expect @pytest.fixture(scope="function", autouse=True) def before_each_after_each(page: Page): print("before the test runs") # Go to the starting url before each test. page.goto("https://playwright.dev/") yield print("after the test runs") def test_main_navigation(page: Page): # Assertions use the expect API. expect(page).to_have_url("https://playwright.dev/") ``` -------------------------------- ### Create auth.setup.ts to authenticate and save storage state Source: https://github.com/microsoft/playwright/blob/main/docs/src/auth.md Use this setup file to perform login steps once and save the authenticated browser state to a JSON file. Replace the example login actions with your own authentication flow. The saved state is later reused via storageState. ```javascript import { test as setup, expect } from '@playwright/test'; import path from 'path'; const authFile = path.join(__dirname, '../playwright/.auth/user.json'); setup('authenticate', async ({ page }) => { // Perform authentication steps. Replace these actions with your own. await page.goto('https://github.com/login'); await page.getByLabel('Username or email address').fill('username'); await page.getByLabel('Password').fill('password'); await page.getByRole('button', { name: 'Sign in' }).click(); // Wait until the page receives the cookies. // // Sometimes login flow sets cookies in the process of several redirects. // Wait for the final URL to ensure that the cookies are actually set. await page.waitForURL('https://github.com/'); // Alternatively, you can wait until the page reaches a state where all cookies are set. await expect(page.getByRole('button', { name: 'View profile and more' })).toBeVisible(); // End of authentication steps. await page.context().storageState({ path: authFile }); }); ``` -------------------------------- ### Record trace in NUnit using BrowserContext.Tracing Source: https://github.com/microsoft/playwright/blob/main/docs/src/trace-viewer-intro-csharp.md Start tracing in the SetUp hook with screenshots, snapshots, and sources enabled, and save the trace file in TearDown. ```csharp namespace PlaywrightTests; [Parallelizable(ParallelScope.Self)] [TestFixture] public class Tests : PageTest { [SetUp] public async Task Setup() { await Context.Tracing.StartAsync(new() { Title = $"{TestContext.CurrentContext.Test.ClassName}.{TestContext.CurrentContext.Test.Name}", Screenshots = true, Snapshots = true, Sources = true }); } [TearDown] public async Task TearDown() { await Context.Tracing.StopAsync(new() { Path = Path.Combine( TestContext.CurrentContext.WorkDirectory, "playwright-traces", $"{TestContext.CurrentContext.Test.ClassName}.{TestContext.CurrentContext.Test.Name}.zip" ) }); } [Test] public async Task GetStartedLink() { // .. } } ``` -------------------------------- ### Define setup project in playwright.config.ts Source: https://github.com/microsoft/playwright/blob/main/docs/src/test-global-setup-teardown-js.md Configure a setup project matching the setup test file using testMatch in the Playwright configuration. ```js import { defineConfig } from '@playwright/test'; export default defineConfig({ testDir: './tests', // ... projects: [ { name: 'setup db', testMatch: /global\.setup\.ts/, }, // { // other project // } ] }); ``` -------------------------------- ### Install dependencies and run build in watch mode Source: https://github.com/microsoft/playwright/blob/main/CONTRIBUTING.md Install clean dependencies via npm ci, run the continuous watch build, and install required browsers. Note that watch mode automatically regenerates certain files. ```bash npm ci npm run watch npx playwright install ``` -------------------------------- ### Set up WebView2Test base class and example test in C# Source: https://github.com/microsoft/playwright/blob/main/docs/src/webview2.md Defines a custom Playwright test fixture that launches the WebView2 executable with CDP debugging enabled and connects to it, followed by an example test class inheriting from it. Use this setup to automate and assert against WebView2 desktop applications in .NET. ```csharp using System.Diagnostics; using Microsoft.Playwright; using Microsoft.Playwright.Xunit.v3; namespace PlaywrightTests; public class WebView2Test : PlaywrightTest { public IBrowser Browser { get; internal set; } = null!; public IBrowserContext Context { get; internal set; } = null!; public IPage Page { get; internal set; } = null!; private Process? _webView2Process = null; private string _userDataDir = null!; private string _executablePath = Path.Join(Directory.GetCurrentDirectory(), @"..\..\..\..\webview2-app\bin\Debug\net8.0-windows\webview2.exe"); public override async Task InitializeAsync() { await base.InitializeAsync(); var cdpPort = 10000 + WorkerIndex; Assert.True(File.Exists(_executablePath), "Make sure that the executable exists"); _userDataDir = Path.Join(Path.GetTempPath(), $"playwright-webview2-tests/user-data-dir-{WorkerIndex}"); // WebView2 does some lazy cleanups on shutdown so we can't clean it up after each test if (Directory.Exists(_userDataDir)) { Directory.Delete(_userDataDir, true); } _webView2Process = Process.Start(new ProcessStartInfo(_executablePath) { EnvironmentVariables = { ["WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS"] = $"--remote-debugging-port={cdpPort}", ["WEBVIEW2_USER_DATA_FOLDER"] = _userDataDir, }, RedirectStandardOutput = true, }); while (!_webView2Process!.HasExited) { var output = await _webView2Process!.StandardOutput.ReadLineAsync(); if (_webView2Process!.HasExited) { throw new Exception("WebView2 process exited unexpectedly"); } if (output != null && output.Contains("WebView2 initialized")) { break; } } var cdpAddress = $"http://127.0.0.1:{cdpPort}"; Browser = await Playwright.Chromium.ConnectOverCDPAsync(cdpAddress); Context = Browser.Contexts[0]; Page = Context.Pages[0]; } public override async Task DisposeAsync() { _webView2Process!.Kill(true); await Browser.CloseAsync(); await base.DisposeAsync(); } } ``` ```csharp using Microsoft.Playwright; using Microsoft.Playwright.Xunit.v3; namespace PlaywrightTests; public class ExampleTest : WebView2Test { [Fact] public async Task HomepageHasPlaywrightInTitleAndGetStartedLinkLinkingtoTheIntroPage() { await Page.GotoAsync("https://playwright.dev"); var getStarted = Page.GetByText("Get Started"); await Expect(getStarted).ToBeVisibleAsync(); } } ``` -------------------------------- ### Codegen Examples Source: https://github.com/microsoft/playwright/blob/main/docs/src/test-cli-js.md Start recording with the interactive UI, record on a specific site, or generate Python code using --target=python. ```bash # Start recording with interactive UI npx playwright codegen # Record on specific site npx playwright codegen https://playwright.dev # Generate Python code npx playwright codegen --target=python ``` -------------------------------- ### Install Playwright with uv Source: https://github.com/microsoft/playwright/blob/main/docs/src/library-python.md Updates uv, adds Playwright to the environment, and installs the required browser binaries. ```bash uv self update uv add playwright playwright install ``` -------------------------------- ### WebMCP Tools List Example Source: https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/skills/playwright-cli/SKILL.md Example output from webmcp-list showing page-provided tools with their schemas and annotations. ```yaml - webmcp tools (page-provided, untrusted): - search [readOnly]: Searches the catalog - inputSchema: {"type":"object","properties":{"query":{"type":"string"}}} - add_to_cart: Adds a product to the cart ``` -------------------------------- ### Write a Playwright Test with test and expect Source: https://github.com/microsoft/playwright/blob/main/README.md Defines two tests using web-first assertions: checking the page title and clicking the 'Get started' link then verifying the Installation heading is visible. ```TypeScript import { test, expect } from '@playwright/test'; test('has title', async ({ page }) => { await page.goto('https://playwright.dev/'); await expect(page).toHaveTitle(/Playwright/); }); test('get started link', async ({ page }) => { await page.goto('https://playwright.dev/'); await page.getByRole('link', { name: 'Get started' }).click(); await expect(page.getByRole('heading', { name: 'Installation' })).toBeVisible(); }); ``` -------------------------------- ### Install Browsers Examples Source: https://github.com/microsoft/playwright/blob/main/docs/src/test-cli-js.md Common npx playwright install invocations: install all browsers, only Chromium, specific browsers, or browsers with system dependencies. ```bash # Install all browsers npx playwright install # Install only Chromium npx playwright install chromium # Install specific browsers npx playwright install chromium webkit # Install browsers with dependencies npx playwright install --with-deps ``` -------------------------------- ### List supported browsers using Python CLI Source: https://github.com/microsoft/playwright/blob/main/docs/src/browsers.md Run the install command with the --help flag to view all supported browser installation options. ```bash playwright install --help ``` -------------------------------- ### Create a page, navigate, and take a screenshot Source: https://github.com/microsoft/playwright/blob/main/docs/src/api/class-page.md This example launches a WebKit browser, creates a new context and page, navigates to 'https://example.com', and saves a screenshot as 'screenshot.png'. It demonstrates the basic workflow for interacting with a page. ```javascript const { webkit } = require('playwright'); // Or 'chromium' or 'firefox'. (async () => { const browser = await webkit.launch(); const context = await browser.newContext(); const page = await context.newPage(); await page.goto('https://example.com'); await page.screenshot({ path: 'screenshot.png' }); await browser.close(); })(); ``` ```java import com.microsoft.playwright.*; public class Example { public static void main(String[] args) { try (Playwright playwright = Playwright.create()) { BrowserType webkit = playwright.webkit(); Browser browser = webkit.launch(); BrowserContext context = browser.newContext(); Page page = context.newPage(); page.navigate("https://example.com"); page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("screenshot.png"))); browser.close(); } } } ``` ```python import asyncio from playwright.async_api import async_playwright, Playwright async def run(playwright: Playwright): webkit = playwright.webkit browser = await webkit.launch() context = await browser.new_context() page = await context.new_page() await page.goto("https://example.com") await page.screenshot(path="screenshot.png") await browser.close() async def main(): async with async_playwright() as playwright: await run(playwright) asyncio.run(main()) ``` ```python from playwright.sync_api import sync_playwright, Playwright def run(playwright: Playwright): webkit = playwright.webkit browser = webkit.launch() context = browser.new_context() page = context.new_page() page.goto("https://example.com") page.screenshot(path="screenshot.png") browser.close() with sync_playwright() as playwright: run(playwright) ``` ```csharp 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" }); } } ``` -------------------------------- ### Initialize skills and prompt coding agent for component testing setup Source: https://github.com/microsoft/playwright/blob/main/docs/src/test-components-js.md Install Playwright skills and instruct your coding agent to set up component testing. The agent configures the gallery, Playwright config, and creates an initial story and test. ```bash npx playwright init-skills ``` ```txt Set up component testing using the playwright-component-testing skill. ``` -------------------------------- ### Install Playwright in CI (Python) Source: https://github.com/microsoft/playwright/blob/main/docs/src/ci.md Install the Playwright Python package and browsers with system dependencies in a CI environment. ```bash pip install playwright playwright install --with-deps ``` -------------------------------- ### List supported browsers using Node.js CLI Source: https://github.com/microsoft/playwright/blob/main/docs/src/browsers.md Run the install command with the --help flag to view all supported browser installation options. ```bash npx playwright install --help ``` -------------------------------- ### Install Playwright in CI (JavaScript) Source: https://github.com/microsoft/playwright/blob/main/docs/src/ci.md Install NPM packages and Playwright browsers with system dependencies in a JavaScript CI environment. ```bash # Install NPM packages npm ci # Install Playwright browsers and dependencies npx playwright install --with-deps ``` -------------------------------- ### Example test that starts authenticated Source: https://github.com/microsoft/playwright/blob/main/docs/src/auth.md Because storageState is set in the config, this test starts with an authenticated page context. No additional login steps are needed in the test itself. ```javascript import { test } from '@playwright/test'; test('test', async ({ page }) => { // page is authenticated }); ``` -------------------------------- ### async method: Credentials.install Source: https://github.com/microsoft/playwright/blob/main/docs/src/api/class-credentials.md Installs the virtual WebAuthn authenticator into the context, overriding navigator.credentials.create() and navigator.credentials.get() in all current and future pages. Must be called before the page first touches navigator.credentials; until then no interception is in place and the page sees the platform's native (or absent) WebAuthn behaviour. ```APIDOC ## async method: Credentials.install ### Description Installs the virtual WebAuthn authenticator into the context, overriding `navigator.credentials.create()` and `navigator.credentials.get()` in all current and future pages. Call this before the page first touches `navigator.credentials`. Required: until `Credentials.install` is called, no interception is in place and the page sees the platform's native (or absent) WebAuthn behaviour. Seeding credentials with `Credentials.create` without installing populates the authenticator, but the page will never see those credentials. ### Method async method: Credentials.install ### Since v1.61 ### Parameters None documented. ### Returns None documented. ``` -------------------------------- ### List supported browsers using Java CLI Source: https://github.com/microsoft/playwright/blob/main/docs/src/browsers.md Pass the --help flag via Maven CLI execution to view all supported browser installation options. ```bash mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI -D exec.args="install --help" ``` -------------------------------- ### Install Playwright in CI (C#) Source: https://github.com/microsoft/playwright/blob/main/docs/src/ci.md Build the .NET project and install Playwright browsers with system dependencies using the generated PowerShell script. ```bash dotnet build pwsh bin/Debug/netX/playwright.ps1 install --with-deps ``` -------------------------------- ### Install Playwright in CI (Java) Source: https://github.com/microsoft/playwright/blob/main/docs/src/ci.md Install Playwright browsers with system dependencies via the Maven exec plugin in a Java CI environment. ```bash mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI -D exec.args="install --with-deps" ``` -------------------------------- ### Install skills globally across projects Source: https://github.com/microsoft/playwright/blob/main/docs/src/getting-started-cli.md Installs skills into the home directory (~/.claude/skills or ~/.agents/skills) to share them across all projects. ```bash playwright-cli install --skills -g ``` -------------------------------- ### Set up and tear down repositories with beforeAll and afterAll Source: https://github.com/microsoft/playwright/blob/main/docs/src/api-testing-js.md Creates a repository before running tests and deletes it afterwards using test.beforeAll and test.afterAll hooks with the request fixture. ```javascript test.beforeAll(async ({ request }) => { // Create a new repository const response = await request.post('/user/repos', { data: { name: REPO } }); expect(response.ok()).toBeTruthy(); }); test.afterAll(async ({ request }) => { // Delete the repository const response = await request.delete(`/repos/${USER}/${REPO}`); expect(response.ok()).toBeTruthy(); }); ``` -------------------------------- ### Capture trace on failures during global setup Source: https://github.com/microsoft/playwright/blob/main/docs/src/test-global-setup-teardown-js.md Wraps globalSetup actions in a try...catch block to start and stop Playwright tracing, ensuring failed setups save a trace file before throwing. ```typescript import { chromium, type FullConfig } from '@playwright/test'; async function globalSetup(config: FullConfig) { const { baseURL, storageState } = config.projects[0].use; const browser = await chromium.launch(); const context = await browser.newContext(); const page = await context.newPage(); try { await context.tracing.start({ screenshots: true, snapshots: true }); await page.goto(baseURL!); await page.getByLabel('User Name').fill('user'); await page.getByLabel('Password').fill('password'); await page.getByText('Sign in').click(); await context.storageState({ path: storageState as string }); await context.tracing.stop({ path: './test-results/setup-trace.zip', }); await browser.close(); } catch (error) { await context.tracing.stop({ path: './test-results/failed-setup-trace.zip', }); await browser.close(); throw error; } } export default globalSetup; ``` -------------------------------- ### Credentials.InstallAsync Source: https://github.com/microsoft/playwright/blob/main/docs/src/api/class-credentials.md Installs the created credentials into the browser context, making them available for passkey authentication flows such as navigator.credentials.get(). ```APIDOC ## Credentials.InstallAsync ### Description Installs the credentials created via `Credentials.CreateAsync()` into the browser context. After installation, the virtual authenticator is active and passkey operations will resolve using the installed credentials. ### Method `InstallAsync` ### Parameters None. ### Example ```csharp await context.Credentials.InstallAsync(); ``` ``` -------------------------------- ### Install default browsers using Python CLI Source: https://github.com/microsoft/playwright/blob/main/docs/src/browsers.md Run the Playwright install command to download the default set of supported browser binaries. ```bash playwright install ``` -------------------------------- ### Set viewport size in Python (async) Source: https://github.com/microsoft/playwright/blob/main/docs/src/api/class-page.md Creates a new page, sets its viewport to 640x480, and navigates to example.com. Use this to ensure the page loads with the desired viewport size. ```python page = await browser.new_page() await page.set_viewport_size({"width": 640, "height": 480}) await page.goto("https://example.com") ``` -------------------------------- ### Run Playwright tests on Azure Pipelines with Python Source: https://github.com/microsoft/playwright/blob/main/docs/src/ci.md Azure Pipelines task that sets up Python 3.13, installs requirements, installs Playwright browsers with dependencies, and runs pytest. ```yaml trigger: - main pool: vmImage: ubuntu-latest steps: - task: UsePythonVersion@0 inputs: versionSpec: '3.13' displayName: 'Use Python' - script: | python -m pip install --upgrade pip pip install -r requirements.txt displayName: 'Install dependencies' - script: playwright install --with-deps displayName: 'Install Playwright browsers' - script: pytest displayName: 'Run Playwright tests' ``` -------------------------------- ### List supported browsers using PowerShell (.NET) Source: https://github.com/microsoft/playwright/blob/main/docs/src/browsers.md Run the PowerShell install script with the --help flag to view all supported browser installation options. ```bash pwsh bin/Debug/netX/playwright.ps1 install --help ``` -------------------------------- ### Configure playwright.config.ts with setup project and storageState Source: https://github.com/microsoft/playwright/blob/main/docs/src/auth.md Declare a setup project that runs auth.setup.ts and make it a dependency of testing projects. Each testing project uses the saved storageState so tests start already authenticated. ```javascript import { defineConfig, devices } from '@playwright/test'; export default defineConfig({ projects: [ // Setup project { name: 'setup', testMatch: /.*\.setup\.ts/ }, { name: 'chromium', use: { ...devices['Desktop Chrome'], // Use prepared auth state. storageState: 'playwright/.auth/user.json', }, dependencies: ['setup'], }, { name: 'firefox', use: { ...devices['Desktop Firefox'], // Use prepared auth state. storageState: 'playwright/.auth/user.json', }, dependencies: ['setup'], }, ], }); ``` -------------------------------- ### Disposable.close Source: https://github.com/microsoft/playwright/blob/main/docs/src/api/class-disposable.md Removes the associated resource in Python. For example, removes an init script installed via Page.addInitScript or BrowserContext.addInitScript. ```APIDOC ## async method: Disposable.close() * **Languages:** Python * **Since:** v1.59 ### Description Removes the associated resource. For example, removes the init script installed via `Page.addInitScript` or `BrowserContext.addInitScript`. ``` -------------------------------- ### Capture a credential and save to file in JavaScript Source: https://github.com/microsoft/playwright/blob/main/docs/src/api/class-credentials.md In a setup test, let the app register a passkey, then read it back with context.credentials.get() and save it to a JSON file for reuse. ```javascript // setup test: let the app register a passkey, then save the storage state with it. const context = await browser.newContext(); await context.credentials.install(); const page = await context.newPage(); await page.goto('https://example.com/register'); await page.getByRole('button', { name: 'Create a passkey' }).click(); // Read back the passkey the page registered — it includes the private key. const [credential] = await context.credentials.get({ rpId: 'example.com' }); fs.writeFileSync('playwright/.auth/passkey.json', JSON.stringify(credential)); ``` -------------------------------- ### Set viewport size in Python (sync) Source: https://github.com/microsoft/playwright/blob/main/docs/src/api/class-page.md Creates a new page, sets its viewport to 640x480, and navigates to example.com. Use this to ensure the page loads with the desired viewport size. ```python page = browser.new_page() page.set_viewport_size({"width": 640, "height": 480}) page.goto("https://example.com") ``` -------------------------------- ### Disposable.dispose Source: https://github.com/microsoft/playwright/blob/main/docs/src/api/class-disposable.md Removes the associated resource in JavaScript. For example, removes an init script installed via Page.addInitScript or BrowserContext.addInitScript. ```APIDOC ## async method: Disposable.dispose() * **Languages:** JavaScript * **Since:** v1.59 ### Description Removes the associated resource. For example, removes the init script installed via `Page.addInitScript` or `BrowserContext.addInitScript`. ``` -------------------------------- ### Run Playwright tests on Azure Pipelines with Java Source: https://github.com/microsoft/playwright/blob/main/docs/src/ci.md Azure Pipelines task that installs JDK 25, builds with Maven, installs Playwright browsers via the CLI, and runs tests. ```yaml trigger: - main pool: vmImage: ubuntu-latest steps: - task: JavaToolInstaller@1 inputs: versionSpec: '25' jdkArchitectureOption: 'x64' jdkSourceOption: AzureStorage - script: mvn -B install -D skipTests --no-transfer-progress displayName: 'Build and install' - script: mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI -D exec.args="install --with-deps" displayName: 'Install Playwright browsers' - script: mvn test displayName: 'Run tests' ``` -------------------------------- ### Install default browsers using Node.js CLI Source: https://github.com/microsoft/playwright/blob/main/docs/src/browsers.md Run the install command without arguments to download the default set of supported browser binaries. ```bash npx playwright install ``` -------------------------------- ### Run Playwright tests: common examples Source: https://github.com/microsoft/playwright/blob/main/docs/src/test-cli-js.md Examples for running all tests, a single file, a set of files, a specific line, by title, in headed mode, for a specific project, or getting help. ```bash # Run all tests npx playwright test # Run a single test file npx playwright test tests/todo-page.spec.ts # Run a set of test files npx playwright test tests/todo-page/ tests/landing-page/ # Run tests at a specific line npx playwright test my-spec.ts:42 # Run tests by title npx playwright test -g "add a todo item" # Run tests in headed browsers npx playwright test --headed # Run tests for a specific project npx playwright test --project=chromium # Get help npx playwright test --help ``` -------------------------------- ### Managing setup and teardown without fixtures using hooks and Page Object Model Source: https://github.com/microsoft/playwright/blob/main/docs/src/test-fixtures-js.md Illustrates the traditional approach to test environment setup using `beforeEach` and `afterEach` lifecycle hooks with a `TodoPage` Page Object Model class (`todo-page.ts` and `todo.spec.ts`). ```javascript import type { Page, Locator } from '@playwright/test'; export class TodoPage { private readonly inputBox: Locator; private readonly todoItems: Locator; constructor(public readonly page: Page) { this.inputBox = this.page.locator('input.new-todo'); this.todoItems = this.page.getByTestId('todo-item'); } async goto() { await this.page.goto('https://demo.playwright.dev/todomvc/'); } async addToDo(text: string) { await this.inputBox.fill(text); await this.inputBox.press('Enter'); } async remove(text: string) { const todo = this.todoItems.filter({ hasText: text }); await todo.hover(); await todo.getByLabel('Delete').click(); } async removeAll() { while ((await this.todoItems.count()) > 0) { await this.todoItems.first().hover(); await this.todoItems.getByLabel('Delete').first().click(); } } } ``` ```javascript const { test } = require('@playwright/test'); const { TodoPage } = require('./todo-page'); test.describe('todo tests', () => { let todoPage; test.beforeEach(async ({ page }) => { todoPage = new TodoPage(page); await todoPage.goto(); await todoPage.addToDo('item1'); await todoPage.addToDo('item2'); }); test.afterEach(async () => { await todoPage.removeAll(); }); test('should add an item', async () => { await todoPage.addToDo('my item'); // ... }); test('should remove an item', async () => { await todoPage.remove('item1'); // ... }); }); ``` -------------------------------- ### Control time with the Clock API: install, pause, and fast-forward Source: https://github.com/microsoft/playwright/blob/main/docs/src/release-notes-csharp.md Use Page.Clock to manipulate time in tests. Install a starting time, pause at a point, then fast-forward to verify time-related behavior. ```csharp // Initialize clock with some time before the test time and let the page load naturally. // `Date.now` will progress as the timers fire. await Page.Clock.InstallAsync(new() { TimeDate = new DateTime(2024, 2, 2, 8, 0, 0) }); await Page.GotoAsync("http://localhost:3333"); // Pretend that the user closed the laptop lid and opened it again at 10am. // Pause the time once reached that point. await Page.Clock.PauseAtAsync(new DateTime(2024, 2, 2, 10, 0, 0)); // Assert the page state. await Expect(Page.GetByTestId("current-time")).ToHaveTextAsync("2/2/2024, 10:00:00 AM"); // Close the laptop lid again and open it at 10:30am. await Page.Clock.FastForwardAsync("30:00"); await Expect(Page.GetByTestId("current-time")).ToHaveTextAsync("2/2/2024, 10:30:00 AM"); ``` -------------------------------- ### Browser.disconnected Source: https://github.com/microsoft/playwright/blob/main/docs/src/api/class-browser.md Event emitted when the Browser gets disconnected from the browser application, for example because the browser application closed or crashed, or because Browser.close was called. ```APIDOC ## event: Browser.disconnected ### Description Emitted when Browser gets disconnected from the browser application. This might happen because of one of the following: - Browser application is closed or crashed. - The `Browser.close` method was called. ### Event Browser.disconnected ### Parameters - **browser** (Browser) - The browser that was disconnected. ### Since v1.8 ``` -------------------------------- ### context.tracing.start Source: https://github.com/microsoft/playwright/blob/main/docs/src/api/class-tracing.md Starts recording a trace. Call this before performing actions you want captured in the trace. Options such as screenshots and snapshots can be enabled. ```APIDOC ## context.tracing.start ### Description Starts recording a trace. Start recording a trace before performing actions so that browser operations and network activity are captured. ### Method `context.tracing.start(options)` ### Parameters - **screenshots** (boolean) - Optional - Whether to capture screenshots during tracing. - **snapshots** (boolean) - Optional - Whether to capture DOM snapshots during tracing. ### Example ```js const browser = await chromium.launch(); const context = await browser.newContext(); await context.tracing.start({ screenshots: true, snapshots: true }); const page = await context.newPage(); await page.goto('https://playwright.dev'); expect(page.url()).toBe('https://playwright.dev'); await context.tracing.stop({ path: 'trace.zip' }); ``` ``` -------------------------------- ### Install specific browser using Java CLI Source: https://github.com/microsoft/playwright/blob/main/docs/src/browsers.md Pass a browser name argument such as webkit through Maven to install only that specific browser binary. ```bash mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI -D exec.args="install webkit" ``` -------------------------------- ### Screencast.start Source: https://github.com/microsoft/playwright/blob/main/docs/src/api/class-screencast.md Starts the screencast. When path is provided, it saves video recording to the specified file. When onFrame is provided, delivers JPEG-encoded frames to the callback. Both can be used together. Returns a Disposable. ```APIDOC ## Screencast.start ### Description Starts the screencast. When `path` is provided, it saves video recording to the specified file. When `onFrame` is provided, delivers JPEG-encoded frames to the callback. Both can be used together. ### Method `async method: Screencast.start` ### Parameters #### Options - **fps** (int) - Optional - Frame rate of the video recording in frames per second. Only used together with `path`. Defaults to `25`. - **onFrame** (function) - Optional - Callback that receives JPEG-encoded frame data along with the page viewport size at the time of capture. The callback receives an object with: - **data** (Buffer) - JPEG-encoded frame data. - **timestamp** (float) - The timestamp of when the frame was presented by the browser, in milliseconds since the Unix epoch. - **viewportWidth** (int) - Width of the page viewport at the time the frame was captured. - **viewportHeight** (int) - Height of the page viewport at the time the frame was captured. - **path** (path) - Optional - Path where the video should be saved when the screencast is stopped. When provided, video recording is started. - **quality** (int) - Optional - The quality of the image, between 0-100. - **size** (Object) - Optional - Specifies the dimensions of screencast frames. The actual frame is scaled to preserve the page's aspect ratio and may be smaller than these bounds. If a screencast is already active, the existing configuration takes precedence. If not specified, the size will be equal to page viewport scaled down to fit into 800×800. - **width** (int) - Max frame width in pixels. - **height** (int) - Max frame height in pixels. ### Returns - **Disposable** - A disposable object to manage the screencast session. ### Example ```js // Record video await page.screencast.start({ path: 'video.webm', size: { width: 1280, height: 800 } }); // ... perform actions ... await page.screencast.stop(); ``` ```js // Capture frames await page.screencast.start({ onFrame: ({ data, timestamp, viewportWidth, viewportHeight }) => { console.log(`frame size: ${data.length} (${viewportWidth}x${viewportHeight}) at ${timestamp}`); }, size: { width: 800, height: 600 }, }); // ... perform actions ... await page.screencast.stop(); ``` ``` -------------------------------- ### Run Playwright tests on Azure Pipelines with Node.js Source: https://github.com/microsoft/playwright/blob/main/docs/src/ci.md Azure Pipelines task for Windows/macOS/Linux agents that installs Node.js 22, runs npm ci, installs Playwright browsers with dependencies, and runs tests with CI=true. ```yaml trigger: - main pool: vmImage: ubuntu-latest steps: - task: UseNode@1 inputs: version: '22' displayName: 'Install Node.js' - script: npm ci displayName: 'npm ci' - script: npx playwright install --with-deps displayName: 'Install Playwright browsers' - script: npx playwright test displayName: 'Run Playwright tests' env: CI: 'true' ``` -------------------------------- ### Configure project teardown in playwright.config.ts Source: https://github.com/microsoft/playwright/blob/main/docs/src/release-notes-js.md Use the `teardown` property to specify a project that runs after this project and all dependent projects finish. The example shows a setup project with a corresponding teardown project, and browser projects that depend on setup. ```javascript import { defineConfig } from '@playwright/test'; export default defineConfig({ projects: [ { name: 'setup', testMatch: /global.setup\.ts/, teardown: 'teardown', }, { name: 'teardown', testMatch: /global.teardown\.ts/, }, { name: 'chromium', use: devices['Desktop Chrome'], dependencies: ['setup'], }, { name: 'firefox', use: devices['Desktop Firefox'], dependencies: ['setup'], }, { name: 'webkit', use: devices['Desktop Safari'], dependencies: ['setup'], }, ], }); ``` -------------------------------- ### Credentials.install Source: https://github.com/microsoft/playwright/blob/main/docs/src/api/class-credentials.md Installs the virtual authenticator into the browser context. After installation, the page's WebAuthn API calls (navigator.credentials.create() and navigator.credentials.get()) will be handled by the virtual authenticator using the stored credentials. ```APIDOC ## Credentials.install ### Description Installs the virtual authenticator into the browser context. Once installed, WebAuthn ceremonies in the page will be answered using the credentials managed by this instance. ### Method `install` ### Parameters None. ### Returns - Promise - Resolves when the authenticator is installed. ### Example ```js await context.credentials.install(); ``` ``` -------------------------------- ### Create context, resize viewport, and emulate high-DPI (Python async) Source: https://github.com/microsoft/playwright/blob/main/docs/src/emulation.md Creates a context with a 1280x1024 viewport, resizes an individual page to 1600x1200, and creates a high-DPI context with a 2560x1440 viewport and device_scale_factor 2 using the async API. ```python # Create context with given viewport context = await browser.new_context( viewport={ 'width': 1280, 'height': 1024 } ) # Resize viewport for individual page await page.set_viewport_size({"width": 1600, "height": 1200}) # Emulate high-DPI context = await browser.new_context( viewport={ 'width': 2560, 'height': 1440 }, device_scale_factor=2, ) ``` -------------------------------- ### Control time with page.clock install, pause_at, and fast_forward Source: https://github.com/microsoft/playwright/blob/main/docs/src/release-notes-python.md Use the Clock API to install a predefined time, pause at a specific moment, and fast-forward timers. The example asserts the page's displayed time after pausing and after fast-forwarding. ```python # Initialize clock with some time before the test time and let the page load # naturally. `Date.now` will progress as the timers fire. page.clock.install(time=datetime.datetime(2024, 2, 2, 8, 0, 0)) page.goto("http://localhost:3333") # Pretend that the user closed the laptop lid and opened it again at 10am. # Pause the time once reached that point. page.clock.pause_at(datetime.datetime(2024, 2, 2, 10, 0, 0)) # Assert the page state. expect(page.get_by_test_id("current-time")).to_have_text("2/2/2024, 10:00:00 AM") # Close the laptop lid again and open it at 10:30am. page.clock.fast_forward("30:00") expect(page.get_by_test_id("current-time")).to_have_text("2/2/2024, 10:30:00 AM") ``` -------------------------------- ### Default Playwright project scaffold Source: https://github.com/microsoft/playwright/blob/main/docs/src/intro-js.md Displays the files and directories created by Playwright upon installation, including the central configuration file and example tests. ```bash playwright.config.ts # Test configuration package.json package-lock.json # Or yarn.lock / pnpm-lock.yaml tests/ example.spec.ts # Minimal example test ``` -------------------------------- ### Set viewport size in Java Source: https://github.com/microsoft/playwright/blob/main/docs/src/api/class-page.md Creates a new page, sets its viewport to 640x480, and navigates to example.com. Use this to ensure the page loads with the desired viewport size. ```java Page page = browser.newPage(); page.setViewportSize(640, 480); page.navigate("https://example.com"); ``` -------------------------------- ### Install Playwright Test with npm init playwright@latest Source: https://github.com/microsoft/playwright/blob/main/README.md Scaffolds a new Playwright Test project using the official initializer. ```bash npm init playwright@latest ``` -------------------------------- ### Reporter.onTestBegin Source: https://github.com/microsoft/playwright/blob/main/docs/src/test-reporter-api/class-reporter.md Optional method called after a test has been started in the worker process. Receives the test and its result, which gets populated while the test runs. ```APIDOC ## Reporter.onTestBegin ### Description Called after a test has been started in the worker process. ### Method Reporter.onTestBegin ### Parameters - **test** (TestCase) - Test that has been started. - **result** (TestResult) - Result of the test run, this object gets populated while the test runs. ### Since v1.10 ``` -------------------------------- ### Record using custom setup and Page.pause in Python (Async) Source: https://github.com/microsoft/playwright/blob/main/docs/src/codegen.md Launch a headed browser instance and await page.pause() to open codegen controls in asynchronous Python. Configure custom routing or context options before initiating page pause. ```python import asyncio from playwright.async_api import async_playwright async def main(): async with async_playwright() as p: # Make sure to run headed. browser = await p.chromium.launch(headless=False) # Setup context however you like. context = await browser.new_context() # Pass any options await context.route('**/*', lambda route: route.continue_()) # Pause the page, and start recording manually. page = await context.new_page() await page.pause() asyncio.run(main()) ``` -------------------------------- ### Start Selenium Hub and Node Docker containers Source: https://github.com/microsoft/playwright/blob/main/docs/src/selenium-grid.md Starts the Selenium Hub container and a Chromium node container configured with event bus ports and node grid URL pointing to the hub IP. ```bash docker run -d -p 4442-4444:4442-4444 --name selenium-hub selenium/hub:4.25.0 docker run -d -p 5555:5555 \ --shm-size="2g" \ -e SE_EVENT_BUS_HOST= \ -e SE_EVENT_BUS_PUBLISH_PORT=4442 \ -e SE_EVENT_BUS_SUBSCRIBE_PORT=4443 \ -e SE_NODE_GRID_URL="http://:4444" selenium/node-chromium:4.25.0 ``` -------------------------------- ### Locator.all to iterate over matching elements in Java Source: https://github.com/microsoft/playwright/blob/main/docs/src/release-notes-java.md Use Locator.all to get a list of all matching locators and iterate over them. The example checks all checkboxes on the page. ```java // Check all checkboxes! Locator checkboxes = page.getByRole(AriaRole.CHECKBOX); for (Locator checkbox : checkboxes.all()) checkbox.check(); ``` -------------------------------- ### Locator.all to iterate over all matching elements in C# Source: https://github.com/microsoft/playwright/blob/main/docs/src/release-notes-csharp.md Use Locator.all to get all matching elements and iterate over them, for example to check all checkboxes. ```csharp // Check all checkboxes! var checkboxes = Page.GetByRole(AriaRole.Checkbox); foreach (var checkbox in await checkboxes.AllAsync()) await checkbox.CheckAsync(); ``` -------------------------------- ### Create context, resize viewport, and emulate high-DPI (Python sync) Source: https://github.com/microsoft/playwright/blob/main/docs/src/emulation.md Creates a context with a 1280x1024 viewport, resizes an individual page to 1600x1200, and creates a high-DPI context with a 2560x1440 viewport and device_scale_factor 2 using the sync API. ```python # Create context with given viewport context = browser.new_context( viewport={ 'width': 1280, 'height': 1024 } ) # Resize viewport for individual page page.set_viewport_size({"width": 1600, "height": 1200}) # Emulate high-DPI context = browser.new_context( viewport={ 'width': 2560, 'height': 1440 }, device_scale_factor=2, ) ``` -------------------------------- ### Send a GET request using Page.APIRequest in C# Source: https://github.com/microsoft/playwright/blob/main/docs/src/release-notes-csharp.md Use Page.APIRequest to send requests to the server directly from .NET. This example performs a GET request and prints the response status, status text, OK flag, Content-Type header, text body, and a JSON property. ```csharp // Do a GET request on behalf of page var response = await Page.APIRequest.GetAsync("http://example.com/foo.json"); Console.WriteLine(response.Status); Console.WriteLine(response.StatusText); Console.WriteLine(response.Ok); Console.WriteLine(response.Headers["Content-Type"]); Console.WriteLine(await response.TextAsync()); Console.WriteLine((await response.JsonAsync())?.GetProperty("foo").GetString()); ``` -------------------------------- ### Wait for Worker using expect_worker in Python sync Source: https://github.com/microsoft/playwright/blob/main/docs/src/api/class-page.md Use this sync context manager to wait for a Worker event. The example clicks a 'Start worker' button and then prints the worker URL. ```python with page.expect_worker() as worker_info: page.get_by_text("Start worker").click() worker = worker_info.value print(worker.url) ``` -------------------------------- ### Install default browsers using PowerShell (.NET) Source: https://github.com/microsoft/playwright/blob/main/docs/src/browsers.md Run the PowerShell CLI script to download the default set of supported browser binaries. ```bash pwsh bin/Debug/netX/playwright.ps1 install ``` -------------------------------- ### Create console project and install Playwright dependencies Source: https://github.com/microsoft/playwright/blob/main/docs/src/library-csharp.md Initializes a new .NET console project, installs the Microsoft.Playwright package, builds the application, and downloads required browser binaries. ```bash # Create project dotnet new console -n PlaywrightDemo cd PlaywrightDemo # Add project dependency dotnet add package Microsoft.Playwright # Build the project dotnet build # Install required browsers - replace netX with actual output folder name, e.g. net8.0. pwsh bin/Debug/netX/playwright.ps1 install # If the pwsh command does not work (throws TypeNotFound), make sure to use an up-to-date version of PowerShell. dotnet tool update --global PowerShell ``` -------------------------------- ### Wait for Worker using expect_worker in Python async Source: https://github.com/microsoft/playwright/blob/main/docs/src/api/class-page.md Use this async context manager to wait for a Worker event. The example clicks a 'Start worker' button and then prints the worker URL. ```python async with page.expect_worker() as worker_info: await page.get_by_text("Start worker").click() worker = await worker_info.value print(worker.url) ``` -------------------------------- ### Record trace in NUnit using BrowserContext.Tracing Source: https://github.com/microsoft/playwright/blob/main/docs/src/trace-viewer.md Configures trace recording in NUnit using [SetUp] to start tracing with screenshots, snapshots, and sources, and [TearDown] to save the resulting zip archive. ```csharp namespace PlaywrightTests; [Parallelizable(ParallelScope.Self)] [TestFixture] public class Tests : PageTest { [SetUp] public async Task Setup() { await Context.Tracing.StartAsync(new() { Title = TestContext.CurrentContext.Test.ClassName + "." + TestContext.CurrentContext.Test.Name, Screenshots = true, Snapshots = true, Sources = true }); } [TearDown] public async Task TearDown() { // This will produce e.g.: // bin/Debug/net8.0/playwright-traces/PlaywrightTests.Tests.Test1.zip await Context.Tracing.StopAsync(new() { Path = Path.Combine( TestContext.CurrentContext.WorkDirectory, "playwright-traces", $"{TestContext.CurrentContext.Test.ClassName}.{TestContext.CurrentContext.Test.Name}.zip" ) }); } [Test] public async Task TestYourOnlineShop() { // .. } } ``` -------------------------------- ### Wait for download event in JavaScript Source: https://github.com/microsoft/playwright/blob/main/docs/src/api/class-page.md Start waiting for the 'download' event before clicking, then await the promise to get the download object. Note that `page.waitForEvent` returns a promise that resolves with the event data. ```javascript // Start waiting for download before clicking. Note no await. const downloadPromise = page.waitForEvent('download'); await page.getByText('Download file').click(); const download = await downloadPromise; ```