playwright-cli run-code syntax and basic usage
The `run-code` CLI command executes arbitrary Playwright code for advanced scenarios not covered by other CLI commands. The syntax is `playwright-cli run-code "async page => { // Your Playwright code here }"`. The code must be a single function expression that receives a page object. The code is wrapped in parentheses and evaluated. Import/export/require syntax is not supported.
playwright-cli run-code with external file
Playwright code can be loaded from an external file using the `--filename` option: `playwright-cli run-code --filename=./my-script.js`. The file should contain a single function expression.
Geolocation permission and coordinates in run-code
To grant geolocation permission and set location, use `await page.context().grantPermissions(['geolocation'])` followed by `await page.context().setGeolocation({ latitude: <number>, longitude: <number> })`. To clear geolocation override, call `await page.context().clearPermissions()`. Example coordinates: London is latitude 51.5074, longitude -0.1278; San Francisco is latitude 37.7749, longitude -122.4194.
Grant multiple browser permissions in run-code
Use `await page.context().grantPermissions([...])` to grant multiple permissions at once. Available permissions include 'geolocation', 'notifications', 'camera', and 'microphone'. Permissions can be scoped to a specific origin using the option `{ origin: 'https://example.com' }`.
Media emulation in run-code
Use `await page.emulateMedia({ ... })` to emulate media features. Options include: `colorScheme` ('dark' or 'light'), `reducedMotion` ('reduce'), and `media` ('print').
Working with iframes in run-code
To access an iframe, use `page.locator('iframe#my-iframe').contentFrame()` to get the frame object, then use locators on that frame. To get all frames on a page, use `page.frames()` which returns an array of frame objects, and call `.url()` on each frame to get its URL.
Handle file downloads in run-code
To handle file downloads, create a promise with `const downloadPromise = page.waitForEvent('download')`, then trigger the download by clicking an element, and await the promise with `const download = await downloadPromise`. Use `await download.saveAs('./path/to/file')` to save the file and `download.suggestedFilename()` to get the suggested filename.
Clipboard operations in run-code
To read clipboard, first grant permission with `await page.context().grantPermissions(['clipboard-read'])`, then use `await page.evaluate(() => navigator.clipboard.readText())`. To write to clipboard, use `await page.evaluate(text => navigator.clipboard.writeText(text), 'text to write')`.
Extract page information in run-code
Common page information methods: `await page.title()` returns the page title; `page.url()` returns the current URL; `await page.content()` returns the full page HTML; `page.viewportSize()` returns the viewport dimensions as an object.
Execute JavaScript in run-code with page.evaluate
Use `await page.evaluate(() => { /* JavaScript code */ })` to execute arbitrary JavaScript in the page context and return a result. Pass arguments to the evaluated function as additional parameters: `await page.evaluate((arg1, arg2) => { /* code */ }, value1, value2)`.
Error handling in run-code
Use try-catch blocks directly in run-code to handle errors. Example: `try { await page.getByRole('button', { name: 'Submit' }).click({ timeout: 1000 }); return 'success'; } catch (e) { return 'error'; }`.
Run tests with multiple workers in xUnit v3
To run xUnit v3 tests with multiple threads, use: `dotnet test -- xUnit.MaxParallelThreads=5`. xUnit v3 uses the conservative parallelism algorithm by default.
Run all tests with dotnet test
To run all tests in a Playwright C# project, use the command `dotnet test`.
Run tests with multiple workers in MSTest
To run MSTest tests with multiple workers, use: `dotnet test -- MSTest.Parallelize.Workers=5`.
Run tests in headed mode with HEADED environment variable
To run tests in headed mode (opening a browser window), set the HEADED environment variable to 1. On bash: `HEADED=1 dotnet test`. On batch: `set HEADED=1` then `dotnet test`. On PowerShell: `$env:HEADED="1"` then `dotnet test`.
Run tests on specific browser with BROWSER environment variable
To run tests on a specific browser, set the BROWSER environment variable. For example, `BROWSER=webkit dotnet test` runs tests on WebKit. On batch: `set BROWSER=webkit` then `dotnet test`. On PowerShell: `$env:BROWSER="webkit"` then `dotnet test`.
Run tests on specific browser with launch configuration
Specify which browser to run tests on by passing `Playwright.BrowserName=webkit` to dotnet test: `dotnet test -- Playwright.BrowserName=webkit`.
Run tests on multiple browsers using runsettings files
To run tests on multiple browsers, invoke `dotnet test` multiple times with different runsettings files: `dotnet test --settings:chromium.runsettings`, `dotnet test --settings:firefox.runsettings`, and `dotnet test --settings:webkit.runsettings`. Each runsettings file contains an XML structure with a RunSettings root element, a Playwright child element, and a BrowserName child element specifying the browser (e.g., chromium, firefox, or webkit).
Run single test file by class name
To run a single test file, use the filter flag with the class name: `dotnet test --filter "ExampleTest"`.
Run multiple specific test files by class names
To run a set of specific test files, use the filter flag with multiple class names separated by pipes: `dotnet test --filter "ExampleTest1|ExampleTest2"`.
Run specific test by test name
To run a test with a specific title, use the filter flag with Name~ followed by the test title: `dotnet test --filter "Name~GetStartedLink"`.
Run tests with multiple workers in NUnit
To run NUnit tests with multiple workers, use: `dotnet test -- NUnit.NumberOfTestWorkers=5`.
Java headless mode disabled with setHeadless(false)
To run tests in headed mode in Java, pass launch(new BrowserType.LaunchOptions().setHeadless(false)) when launching the browser. By default, tests run in headless mode with no browser window opened.
Run pytest tests in headed mode with --headed flag
To run tests in headed mode, use the --headed flag with pytest. This will open up a browser window while running tests and once finished the browser window will close.
Run pytest tests in headless mode by default
When you run pytest without flags, tests run in headless mode by default, meaning no browser window will be opened while running the tests and results will be seen in the terminal. Tests run on the Chromium browser by default.
Specify browser with --browser flag
To specify which browser to run tests on, use the --browser flag followed by the browser name, such as 'webkit' or 'firefox'. To run tests on multiple browsers, use the --browser flag multiple times, once for each browser.
Run specific test file or files with pytest
To run a single test file, pass the test file name to pytest, for example 'pytest test_login.py'. To run multiple test files, pass all file names, for example 'pytest tests/test_todo_page.py tests/test_landing_page.py'.
Run specific test by name with -k flag
To run a specific test, use the -k flag followed by the test function name, for example 'pytest -k test_add_a_todo_item'.
Run tests in parallel with --numprocesses flag
To run tests in parallel, use the --numprocesses flag followed by the number of processes, for example 'pytest --numprocesses 2'. This requires pytest-xdist to be installed. Half of logical CPU cores is the recommended number of processes.
Playwright Test Healer agent purpose
The Playwright Test Healer is an agent that runs all tests and automatically fixes failing ones.
Running tests during Playwright development
Run tests with: `npm run ctest tests/page/xxx.spec.ts` for Chromium only, `npm run test tests/page/xxx.spec.ts` for all browsers, `npm run ctest -- --grep "pattern"` to filter tests by name pattern.
Client call chain architecture for Playwright API
The call chain flows: user code calls Page.method() which calls Frame.method() which calls this._channel.method(params). The Proxy validates and sends via Connection.sendMessageToServer() across the wire to DispatcherConnection.dispatch(), which routes to XxxDispatcher.method(params, progress), which calls ServerObject.method(progress, ...), which delegates to BrowserDelegate (Chrome DevTools Protocol for Chromium, Firefox protocol, or WebKit protocol).
Test location and fixtures for Playwright development
Page-only tests go in `tests/page/xxx.spec.ts` using the `page` fixture. Context tests go in `tests/library/xxx.spec.ts` using the `context` fixture. Available fixtures include: `page` (isolated page instance), `context` (browser context for library tests), `server` (HTTP test server with properties `server.EMPTY_PAGE`, `server.PREFIX`, `server.CROSS_PROCESS_PREFIX`), `httpsServer` (HTTPS test server), `asset(name)` (path to test asset file), `browserName` ('chromium' | 'firefox' | 'webkit'), `channel` (browser channel string), `isAndroid`, `isBidi`, `isElectron` (platform booleans), `isWindows`, `isMac`, `isLinux` (OS booleans), `mode` (test mode: 'default', 'service', etc.).
Import path for Playwright Test
Import everything from '@playwright/test' for both component and end-to-end tests: const { test, expect } = require('@playwright/test');
Example: Using Playwright.devices for mobile emulation
const { webkit, devices } = require('playwright'); const iPhone = devices['iPhone 6']; (async () => { const browser = await webkit.launch(); const context = await browser.newContext({ ...iPhone }); const page = await context.newPage(); await page.goto('http://example.com'); await browser.close(); })();
Playwright.errors TimeoutError handling
Playwright provides specific error classes via playwright.errors, including TimeoutError. Methods like Locator.waitFor() may throw TimeoutError if selectors do not match nodes within the given timeframe. Errors can be caught using instanceof checks.
Example: Handling Playwright TimeoutError in JavaScript
try { await page.locator('.foo').waitFor(); } catch (e) { if (e instanceof playwright.errors.TimeoutError) { // Do something if this is a timeout. } }
Playwright.selectors for custom selector engines
The Playwright.selectors property allows installation of custom selector engines for extensibility.
Playwright.create() Java method
The Playwright.create() method (Java only) launches a new Playwright driver process and connects to it. Playwright.close() should be called when the instance is no longer needed.
Playwright.stop() Python async method
The Playwright.stop() async method (Python only) terminates a Playwright instance created by bypassing the Python context manager. This is useful in REPL applications.
Example: Python sync_playwright manual lifecycle
from playwright.sync_api import sync_playwright
playwright = sync_playwright().start()
browser = playwright.chromium.launch()
page = browser.new_page()
page.goto("https://playwright.dev/")
page.screenshot(path="example.png")
browser.close()
playwright.stop()
Playwright.devices for device emulation
The Playwright.devices property returns a dictionary of predefined device configurations (such as 'iPhone 6') that can be used with Browser.newContext() or Browser.newPage() to emulate mobile devices and other device types.
Playwright module basic browser launch example
The Playwright module provides methods to launch browser instances. A typical workflow imports chromium, firefox, or webkit, launches a browser with launch(), creates a new page with newPage(), navigates with goto(), performs actions, then closes the browser with close().
Playwright.chromium property
The Playwright.chromium property is a BrowserType object that can be used to launch or connect to Chromium, returning instances of Browser.
Playwright.firefox property
The Playwright.firefox property is a BrowserType object that can be used to launch or connect to Firefox, returning instances of Browser.
Playwright.webkit property
The Playwright.webkit property is a BrowserType object that can be used to launch or connect to WebKit, returning instances of Browser.
Run Playwright tests with JS/TS
To run Playwright tests with JavaScript or TypeScript, use the command 'PLAYWRIGHT_HTML_OPEN=never npx playwright test' or 'PLAYWRIGHT_HTML_OPEN=never npm run special-test-command'. Setting PLAYWRIGHT_HTML_OPEN=never prevents the interactive HTML report from opening automatically.
Run Playwright tests with Python
To run Playwright tests with Python, use the command 'pytest'.