
Playwright Cli
- 6 installs
- 18 repo stars
- Updated May 17, 2026
- appautomaton/webmaton
playwright-cli is a Claude skill exposing a token-efficient shell interface to Playwright for browser automation, inspection, test debugging and test-code generation.
About
playwright-cli is a shell interface to Playwright that keeps browser state across commands and exposes page snapshots with stable element refs. A developer uses it to open or attach to browser sessions, click, type and fill forms, inspect console, network and storage, run snippets, capture screenshots or traces, and debug Playwright tests. It prints the Playwright code it ran so interactions can be turned into test code. It is not meant for static HTTP fetches, JSON APIs or simple web search.
- Token-efficient shell interface to Playwright that keeps browser state across commands
- Snapshots expose stable element refs like e15 for reliable click/type/fill
- Prints the Playwright code it ran so interactions convert into tests
Playwright Cli by the numbers
- 6 all-time installs (skills.sh)
- Ranked #1,591 of 2,153 Testing & QA skills by installs in the Skillselion catalog
- Data as of Jul 28, 2026 (Skillselion catalog sync)
playwright-cli capabilities & compatibility
- Capabilities
- nodriver browser · html to markdown
- Works with
- playwright · chrome
- Use cases
- testing · debugging · web scraping
- Runs
- Runs locally
- Pricing
- Free
What playwright-cli says it does
`playwright-cli` is a token-efficient shell interface to Playwright.
prints the Playwright code it ran so the interaction can be converted into tests.
npx skills add https://github.com/appautomaton/webmaton --skill playwright-cliAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 6 |
|---|---|
| repo stars | ★ 18 |
| Last updated | May 17, 2026 |
| Repository | appautomaton/webmaton ↗ |
What it does
Drive Playwright browser sessions from the shell to inspect, interact, debug tests and generate reliable Playwright test code.
Who is it for?
repeatable browser workflows and Playwright test work
Skip if: static HTTP fetches, JSON APIs, or simple web search
When should I use this skill?
a task needs Playwright browser sessions, form filling, test debugging, traces, screenshots or generated test code
What you get
Stateful browser sessions with stable element refs plus the Playwright code needed to turn interactions into tests.
- browser session state
- page snapshots with refs
- screenshots and traces
By the numbers
- ships 10 reference docs for CLI, tests, tracing and more
Files
playwright-cli
playwright-cli is a token-efficient shell interface to Playwright. It keeps browser state across commands, exposes page snapshots with stable element refs such as e15, and prints the Playwright code it ran so the interaction can be converted into tests.
Core Workflow
playwright-cli open https://example.com
playwright-cli snapshot
playwright-cli click e15
playwright-cli fill e5 "user@example.com"
playwright-cli press Enter
playwright-cli closeUse refs from the latest snapshot by default. Re-run snapshot after navigation, major DOM changes, or a failed ref action. Use CSS selectors or Playwright locators only when refs are unavailable or unstable.
Operating Rules
- Discover exact syntax with
playwright-cli --helpandplaywright-cli <command> --help; the CLI changes quickly. - Use
--rawwhen piping values into other tools. Use--jsononly if the installed CLI advertises it. - Use named sessions with
-s=<name>for concurrent or long-lived work. - Use
open --persistentonly when disk-persisted cookies/storage are needed. - Prefer
attach --cdp=chrome,attach --cdp=msedge, orattach --cdp=http://127.0.0.1:9222when the task needs an existing browser/session. - Close sessions when finished. Reserve
close-allandkill-allfor cleanup of stale sessions.
Common Tasks
playwright-cli open https://example.com --browser=chrome
playwright-cli snapshot --depth=4
playwright-cli screenshot --filename=page.png
playwright-cli console warning
playwright-cli network --filter="/api/.*" --request-headers
playwright-cli run-code "async page => await page.context().grantPermissions(['geolocation'])"
playwright-cli tracing-start
playwright-cli tracing-stopFor a broader command map, read references/cli-reference.md.
Playwright Test Debugging
When a Playwright test fails, prefer the CLI debug workflow:
PLAYWRIGHT_HTML_OPEN=never npx playwright test --debug=cli
# wait for "Debugging Instructions", then attach to the printed session
playwright-cli attach tw-abcdefKeep the test process running while inspecting the paused page. Use snapshots, console/network inspection, and generated Playwright code to identify the fix.
References
Load only what the task needs:
references/cli-reference.md— command groups, output modes, and version-sensitive featuresreferences/playwright-tests.md— running and debugging Playwright testsreferences/request-mocking.md— route mocking and request interceptionreferences/running-code.md— custom Playwright snippets withrun-codereferences/session-management.md— named sessions and cleanupreferences/storage-state.md— cookies, localStorage, sessionStorage, auth statereferences/test-generation.md— turning CLI output into testsreferences/tracing.md— trace capture and inspectionreferences/video-recording.md— WebM recording and chapter markersreferences/element-attributes.md— inspect IDs/classes/data attributes not shown in snapshots
CLI Reference
Use this as a map, not as a substitute for playwright-cli <command> --help.
Session Lifecycle
playwright-cli open [url]
playwright-cli open [url] --browser=chrome|firefox|webkit|msedge
playwright-cli open [url] --headed
playwright-cli open [url] --persistent
playwright-cli open [url] --profile=/path/to/profile
playwright-cli attach --cdp=chrome
playwright-cli attach --cdp=http://127.0.0.1:9222
playwright-cli attach --extension=chrome
playwright-cli list
playwright-cli close
playwright-cli close-all
playwright-cli kill-all
playwright-cli delete-dataUse -s=<session> before the command to isolate concurrent sessions:
playwright-cli -s=auth open https://app.example.com --persistent
playwright-cli -s=auth snapshot
playwright-cli -s=auth closeInspect And Act
playwright-cli snapshot
playwright-cli snapshot e34
playwright-cli snapshot "#main" --depth=4
playwright-cli click e15
playwright-cli dblclick e15
playwright-cli fill e5 "text"
playwright-cli fill e5 "text" --submit
playwright-cli type "text"
playwright-cli type "text" --submit
playwright-cli press Enter
playwright-cli hover e4
playwright-cli drag e2 e8
playwright-cli select e9 "option-value"
playwright-cli check e12
playwright-cli uncheck e12
playwright-cli upload ./document.pdf
playwright-cli eval "document.title"
playwright-cli eval "el => el.getAttribute('data-testid')" e5Refs come from the latest snapshot. If the page navigated or re-rendered, snapshot again.
Navigation, Tabs, And Output
playwright-cli goto https://example.com
playwright-cli go-back
playwright-cli go-forward
playwright-cli reload
playwright-cli tab-list
playwright-cli tab-new https://example.com/other
playwright-cli tab-select 0
playwright-cli tab-close 1
playwright-cli screenshot --filename=page.png
playwright-cli pdf --filename=page.pdf
playwright-cli --raw eval "document.title"Use --json only if playwright-cli --help shows it in the installed version.
Debugging, Network, And Storage
playwright-cli console
playwright-cli console warning
playwright-cli network
playwright-cli network --filter="/api/.*" --request-headers --request-body
playwright-cli network-state-set offline
playwright-cli network-state-set online
playwright-cli run-code "async page => await page.context().clearCookies()"
playwright-cli state-save auth.json
playwright-cli state-load auth.json
playwright-cli cookie-list
playwright-cli localstorage-list
playwright-cli sessionstorage-list
playwright-cli tracing-start
playwright-cli tracing-stop
playwright-cli video-start demo.webm
playwright-cli video-chapter "Step" --description="Context" --duration=2000
playwright-cli video-stopVersion-Sensitive Commands
Recent releases may add commands such as highlight, generate-locator, drop, detach, snapshot --boxes, and global --json. Check playwright-cli --version and command help before using them.
Inspecting Element Attributes
When the snapshot doesn't show an element's id, class, data-* attributes, or other DOM properties, use eval to inspect them.
Examples
playwright-cli snapshot
# snapshot shows a button as e7 but doesn't reveal its id or data attributes
# get the element's id
playwright-cli eval "el => el.id" e7
# get all CSS classes
playwright-cli eval "el => el.className" e7
# get a specific attribute
playwright-cli eval "el => el.getAttribute('data-testid')" e7
playwright-cli eval "el => el.getAttribute('aria-label')" e7
# get a computed style property
playwright-cli eval "el => getComputedStyle(el).display" e7Running Playwright Tests
To run Playwright tests, use the npx playwright test command, or a package manager script. To avoid opening the interactive html report, use PLAYWRIGHT_HTML_OPEN=never environment variable.
# Run all tests
PLAYWRIGHT_HTML_OPEN=never npx playwright test
# Run all tests through a custom npm script
PLAYWRIGHT_HTML_OPEN=never npm run special-test-commandDebugging Playwright Tests
To debug a failing Playwright test, run it with --debug=cli option. This command will pause the test at the start and print the debugging instructions.
IMPORTANT: run the command in the background and check the output until "Debugging Instructions" is printed.
Once instructions containing a session name are printed, use playwright-cli to attach the session and explore the page.
# Run the test
PLAYWRIGHT_HTML_OPEN=never npx playwright test --debug=cli
# ...
# ... debugging instructions for "tw-abcdef" session ...
# ...
# Attach to the test
playwright-cli attach tw-abcdefKeep the test running in the background while you explore and look for a fix. The test is paused at the start, so you should step over or pause at a particular location where the problem is most likely to be.
Every action you perform with playwright-cli generates corresponding Playwright TypeScript code. This code appears in the output and can be copied directly into the test. Most of the time, a specific locator or an expectation should be updated, but it could also be a bug in the app. Use your judgement.
After fixing the test, stop the background test run. Rerun to check that test passes.
Request Mocking
Intercept, mock, modify, and block network requests.
CLI Route Commands
# Mock with custom status
playwright-cli route "**/*.jpg" --status=404
# Mock with JSON body
playwright-cli route "**/api/users" --body='[{"id":1,"name":"Alice"}]' --content-type=application/json
# Mock with custom headers
playwright-cli route "**/api/data" --body='{"ok":true}' --header="X-Custom: value"
# Remove headers from requests
playwright-cli route "**/*" --remove-header=cookie,authorization
# List active routes
playwright-cli route-list
# Remove a route or all routes
playwright-cli unroute "**/*.jpg"
playwright-cli unrouteURL Patterns
**/api/users - Exact path match
**/api/*/details - Wildcard in path
**/*.{png,jpg,jpeg} - Match file extensions
**/search?q=* - Match query parametersAdvanced Mocking with run-code
For conditional responses, request body inspection, response modification, or delays:
Conditional Response Based on Request
playwright-cli run-code "async page => {
await page.route('**/api/login', route => {
const body = route.request().postDataJSON();
if (body.username === 'admin') {
route.fulfill({ body: JSON.stringify({ token: 'mock-token' }) });
} else {
route.fulfill({ status: 401, body: JSON.stringify({ error: 'Invalid' }) });
}
});
}"Modify Real Response
playwright-cli run-code "async page => {
await page.route('**/api/user', async route => {
const response = await route.fetch();
const json = await response.json();
json.isPremium = true;
await route.fulfill({ response, json });
});
}"Simulate Network Failures
playwright-cli run-code "async page => {
await page.route('**/api/offline', route => route.abort('internetdisconnected'));
}"
# Options: connectionrefused, timedout, connectionreset, internetdisconnectedDelayed Response
playwright-cli run-code "async page => {
await page.route('**/api/slow', async route => {
await new Promise(r => setTimeout(r, 3000));
route.fulfill({ body: JSON.stringify({ data: 'loaded' }) });
});
}"Running Custom Playwright Code
Use run-code to execute arbitrary Playwright code for advanced scenarios not covered by CLI commands.
Syntax
playwright-cli run-code "async page => {
// Your Playwright code here
// Access page.context() for browser context operations
}"Geolocation
# Grant geolocation permission and set location
playwright-cli run-code "async page => {
await page.context().grantPermissions(['geolocation']);
await page.context().setGeolocation({ latitude: 37.7749, longitude: -122.4194 });
}"
# Set location to London
playwright-cli run-code "async page => {
await page.context().grantPermissions(['geolocation']);
await page.context().setGeolocation({ latitude: 51.5074, longitude: -0.1278 });
}"
# Clear geolocation override
playwright-cli run-code "async page => {
await page.context().clearPermissions();
}"Permissions
# Grant multiple permissions
playwright-cli run-code "async page => {
await page.context().grantPermissions([
'geolocation',
'notifications',
'camera',
'microphone'
]);
}"
# Grant permissions for specific origin
playwright-cli run-code "async page => {
await page.context().grantPermissions(['clipboard-read'], {
origin: 'https://example.com'
});
}"Media Emulation
# Emulate dark color scheme
playwright-cli run-code "async page => {
await page.emulateMedia({ colorScheme: 'dark' });
}"
# Emulate light color scheme
playwright-cli run-code "async page => {
await page.emulateMedia({ colorScheme: 'light' });
}"
# Emulate reduced motion
playwright-cli run-code "async page => {
await page.emulateMedia({ reducedMotion: 'reduce' });
}"
# Emulate print media
playwright-cli run-code "async page => {
await page.emulateMedia({ media: 'print' });
}"Wait Strategies
# Wait for network idle
playwright-cli run-code "async page => {
await page.waitForLoadState('networkidle');
}"
# Wait for specific element
playwright-cli run-code "async page => {
await page.locator('.loading').waitFor({ state: 'hidden' });
}"
# Wait for function to return true
playwright-cli run-code "async page => {
await page.waitForFunction(() => window.appReady === true);
}"
# Wait with timeout
playwright-cli run-code "async page => {
await page.locator('.result').waitFor({ timeout: 10000 });
}"Frames and Iframes
# Work with iframe
playwright-cli run-code "async page => {
const frame = page.locator('iframe#my-iframe').contentFrame();
await frame.locator('button').click();
}"
# Get all frames
playwright-cli run-code "async page => {
const frames = page.frames();
return frames.map(f => f.url());
}"File Downloads
# Handle file download
playwright-cli run-code "async page => {
const downloadPromise = page.waitForEvent('download');
await page.getByRole('link', { name: 'Download' }).click();
const download = await downloadPromise;
await download.saveAs('./downloaded-file.pdf');
return download.suggestedFilename();
}"Clipboard
# Read clipboard (requires permission)
playwright-cli run-code "async page => {
await page.context().grantPermissions(['clipboard-read']);
return await page.evaluate(() => navigator.clipboard.readText());
}"
# Write to clipboard
playwright-cli run-code "async page => {
await page.evaluate(text => navigator.clipboard.writeText(text), 'Hello clipboard!');
}"Page Information
# Get page title
playwright-cli run-code "async page => {
return await page.title();
}"
# Get current URL
playwright-cli run-code "async page => {
return page.url();
}"
# Get page content
playwright-cli run-code "async page => {
return await page.content();
}"
# Get viewport size
playwright-cli run-code "async page => {
return page.viewportSize();
}"JavaScript Execution
# Execute JavaScript and return result
playwright-cli run-code "async page => {
return await page.evaluate(() => {
return {
userAgent: navigator.userAgent,
language: navigator.language,
cookiesEnabled: navigator.cookieEnabled
};
});
}"
# Pass arguments to evaluate
playwright-cli run-code "async page => {
const multiplier = 5;
return await page.evaluate(m => document.querySelectorAll('li').length * m, multiplier);
}"Error Handling
# Try-catch in run-code
playwright-cli run-code "async page => {
try {
await page.getByRole('button', { name: 'Submit' }).click({ timeout: 1000 });
return 'clicked';
} catch (e) {
return 'element not found';
}
}"Complex Workflows
# Login and save state
playwright-cli run-code "async page => {
await page.goto('https://example.com/login');
await page.getByRole('textbox', { name: 'Email' }).fill('user@example.com');
await page.getByRole('textbox', { name: 'Password' }).fill('secret');
await page.getByRole('button', { name: 'Sign in' }).click();
await page.waitForURL('**/dashboard');
await page.context().storageState({ path: 'auth.json' });
return 'Login successful';
}"
# Scrape data from multiple pages
playwright-cli run-code "async page => {
const results = [];
for (let i = 1; i <= 3; i++) {
await page.goto(\`https://example.com/page/\${i}\`);
const items = await page.locator('.item').allTextContents();
results.push(...items);
}
return results;
}"Browser Session Management
Run multiple isolated browser sessions concurrently with state persistence.
Named Browser Sessions
Use -s flag to isolate browser contexts:
# Browser 1: Authentication flow
playwright-cli -s=auth open https://app.example.com/login
# Browser 2: Public browsing (separate cookies, storage)
playwright-cli -s=public open https://example.com
# Commands are isolated by browser session
playwright-cli -s=auth fill e1 "user@example.com"
playwright-cli -s=public snapshotBrowser Session Isolation Properties
Each browser session has independent:
- Cookies
- LocalStorage / SessionStorage
- IndexedDB
- Cache
- Browsing history
- Open tabs
Browser Session Commands
# List all browser sessions
playwright-cli list
# Stop a browser session (close the browser)
playwright-cli close # stop the default browser
playwright-cli -s=mysession close # stop a named browser
# Stop all browser sessions
playwright-cli close-all
# Forcefully kill all daemon processes (for stale/zombie processes)
playwright-cli kill-all
# Delete browser session user data (profile directory)
playwright-cli delete-data # delete default browser data
playwright-cli -s=mysession delete-data # delete named browser dataEnvironment Variable
Set a default browser session name via environment variable:
export PLAYWRIGHT_CLI_SESSION="mysession"
playwright-cli open example.com # Uses "mysession" automaticallyCommon Patterns
Concurrent Scraping
#!/bin/bash
# Scrape multiple sites concurrently
# Start all browsers
playwright-cli -s=site1 open https://site1.com &
playwright-cli -s=site2 open https://site2.com &
playwright-cli -s=site3 open https://site3.com &
wait
# Take snapshots from each
playwright-cli -s=site1 snapshot
playwright-cli -s=site2 snapshot
playwright-cli -s=site3 snapshot
# Cleanup
playwright-cli close-allA/B Testing Sessions
# Test different user experiences
playwright-cli -s=variant-a open "https://app.com?variant=a"
playwright-cli -s=variant-b open "https://app.com?variant=b"
# Compare
playwright-cli -s=variant-a screenshot
playwright-cli -s=variant-b screenshotPersistent Profile
By default, browser profile is kept in memory only. Use --persistent flag on open to persist the browser profile to disk:
# Use persistent profile (auto-generated location)
playwright-cli open https://example.com --persistent
# Use persistent profile with custom directory
playwright-cli open https://example.com --profile=/path/to/profileAttaching to a Running Browser
Use attach to connect to a browser that is already running, instead of launching a new one.
Attach by channel name
Connect to a running Chrome or Edge instance by its channel name. The browser must have remote debugging enabled — navigate to chrome://inspect/#remote-debugging in the target browser and check "Allow remote debugging for this browser instance".
# Attach to Chrome
playwright-cli attach --cdp=chrome
# Attach to Chrome Canary
playwright-cli attach --cdp=chrome-canary
# Attach to Microsoft Edge
playwright-cli attach --cdp=msedge
# Attach to Edge Dev
playwright-cli attach --cdp=msedge-devSupported channels: chrome, chrome-beta, chrome-dev, chrome-canary, msedge, msedge-beta, msedge-dev, msedge-canary.
Attach via CDP endpoint
Connect to a browser that exposes a Chrome DevTools Protocol endpoint:
playwright-cli attach --cdp=http://localhost:9222Attach via browser extension
Connect to a browser with the Playwright extension installed:
playwright-cli attach --extensionDefault Browser Session
When -s is omitted, commands use the default browser session:
# These use the same default browser session
playwright-cli open https://example.com
playwright-cli snapshot
playwright-cli close # Stops default browserBrowser Session Configuration
Configure a browser session with specific settings when opening:
# Open with config file
playwright-cli open https://example.com --config=.playwright/my-cli.json
# Open with specific browser
playwright-cli open https://example.com --browser=firefox
# Open in headed mode
playwright-cli open https://example.com --headed
# Open with persistent profile
playwright-cli open https://example.com --persistentBest Practices
1. Name Browser Sessions Semantically
# GOOD: Clear purpose
playwright-cli -s=github-auth open https://github.com
playwright-cli -s=docs-scrape open https://docs.example.com
# AVOID: Generic names
playwright-cli -s=s1 open https://github.com2. Always Clean Up
# Stop browsers when done
playwright-cli -s=auth close
playwright-cli -s=scrape close
# Or stop all at once
playwright-cli close-all
# If browsers become unresponsive or zombie processes remain
playwright-cli kill-all3. Delete Stale Browser Data
# Remove old browser data to free disk space
playwright-cli -s=oldsession delete-dataStorage Management
Manage cookies, localStorage, sessionStorage, and browser storage state.
Storage State
Save and restore complete browser state including cookies and storage.
Save Storage State
# Save to auto-generated filename (storage-state-{timestamp}.json)
playwright-cli state-save
# Save to specific filename
playwright-cli state-save my-auth-state.jsonRestore Storage State
# Load storage state from file
playwright-cli state-load my-auth-state.json
# Reload page to apply cookies
playwright-cli open https://example.comStorage State File Format
The saved file contains:
{
"cookies": [
{
"name": "session_id",
"value": "abc123",
"domain": "example.com",
"path": "/",
"expires": 1735689600,
"httpOnly": true,
"secure": true,
"sameSite": "Lax"
}
],
"origins": [
{
"origin": "https://example.com",
"localStorage": [
{ "name": "theme", "value": "dark" },
{ "name": "user_id", "value": "12345" }
]
}
]
}Cookies
List All Cookies
playwright-cli cookie-listFilter Cookies by Domain
playwright-cli cookie-list --domain=example.comFilter Cookies by Path
playwright-cli cookie-list --path=/apiGet Specific Cookie
playwright-cli cookie-get session_idSet a Cookie
# Basic cookie
playwright-cli cookie-set session abc123
# Cookie with options
playwright-cli cookie-set session abc123 --domain=example.com --path=/ --httpOnly --secure --sameSite=Lax
# Cookie with expiration (Unix timestamp)
playwright-cli cookie-set remember_me token123 --expires=1735689600Delete a Cookie
playwright-cli cookie-delete session_idClear All Cookies
playwright-cli cookie-clearAdvanced: Multiple Cookies or Custom Options
For complex scenarios like adding multiple cookies at once, use run-code:
playwright-cli run-code "async page => {
await page.context().addCookies([
{ name: 'session_id', value: 'sess_abc123', domain: 'example.com', path: '/', httpOnly: true },
{ name: 'preferences', value: JSON.stringify({ theme: 'dark' }), domain: 'example.com', path: '/' }
]);
}"Local Storage
List All localStorage Items
playwright-cli localstorage-listGet Single Value
playwright-cli localstorage-get tokenSet Value
playwright-cli localstorage-set theme darkSet JSON Value
playwright-cli localstorage-set user_settings '{"theme":"dark","language":"en"}'Delete Single Item
playwright-cli localstorage-delete tokenClear All localStorage
playwright-cli localstorage-clearAdvanced: Multiple Operations
For complex scenarios like setting multiple values at once, use run-code:
playwright-cli run-code "async page => {
await page.evaluate(() => {
localStorage.setItem('token', 'jwt_abc123');
localStorage.setItem('user_id', '12345');
localStorage.setItem('expires_at', Date.now() + 3600000);
});
}"Session Storage
List All sessionStorage Items
playwright-cli sessionstorage-listGet Single Value
playwright-cli sessionstorage-get form_dataSet Value
playwright-cli sessionstorage-set step 3Delete Single Item
playwright-cli sessionstorage-delete stepClear sessionStorage
playwright-cli sessionstorage-clearIndexedDB
List Databases
playwright-cli run-code "async page => {
return await page.evaluate(async () => {
const databases = await indexedDB.databases();
return databases;
});
}"Delete Database
playwright-cli run-code "async page => {
await page.evaluate(() => {
indexedDB.deleteDatabase('myDatabase');
});
}"Common Patterns
Authentication State Reuse
# Step 1: Login and save state
playwright-cli open https://app.example.com/login
playwright-cli snapshot
playwright-cli fill e1 "user@example.com"
playwright-cli fill e2 "password123"
playwright-cli click e3
# Save the authenticated state
playwright-cli state-save auth.json
# Step 2: Later, restore state and skip login
playwright-cli state-load auth.json
playwright-cli open https://app.example.com/dashboard
# Already logged in!Save and Restore Roundtrip
# Set up authentication state
playwright-cli open https://example.com
playwright-cli eval "() => { document.cookie = 'session=abc123'; localStorage.setItem('user', 'john'); }"
# Save state to file
playwright-cli state-save my-session.json
# ... later, in a new session ...
# Restore state
playwright-cli state-load my-session.json
playwright-cli open https://example.com
# Cookies and localStorage are restored!Security Notes
- Never commit storage state files containing auth tokens
- Add
*.auth-state.jsonto.gitignore - Delete state files after automation completes
- Use environment variables for sensitive data
- By default, sessions run in-memory mode which is safer for sensitive operations
Test Generation
Generate Playwright test code automatically as you interact with the browser.
How It Works
Every action you perform with playwright-cli generates corresponding Playwright TypeScript code. This code appears in the output and can be copied directly into your test files.
Example Workflow
# Start a session
playwright-cli open https://example.com/login
# Take a snapshot to see elements
playwright-cli snapshot
# Output shows: e1 [textbox "Email"], e2 [textbox "Password"], e3 [button "Sign In"]
# Fill form fields - generates code automatically
playwright-cli fill e1 "user@example.com"
# Ran Playwright code:
# await page.getByRole('textbox', { name: 'Email' }).fill('user@example.com');
playwright-cli fill e2 "password123"
# Ran Playwright code:
# await page.getByRole('textbox', { name: 'Password' }).fill('password123');
playwright-cli click e3
# Ran Playwright code:
# await page.getByRole('button', { name: 'Sign In' }).click();Building a Test File
Collect the generated code into a Playwright test:
import { test, expect } from '@playwright/test';
test('login flow', async ({ page }) => {
// Generated code from playwright-cli session:
await page.goto('https://example.com/login');
await page.getByRole('textbox', { name: 'Email' }).fill('user@example.com');
await page.getByRole('textbox', { name: 'Password' }).fill('password123');
await page.getByRole('button', { name: 'Sign In' }).click();
// Add assertions
await expect(page).toHaveURL(/.*dashboard/);
});Best Practices
1. Use Semantic Locators
The generated code uses role-based locators when possible, which are more resilient:
// Generated (good - semantic)
await page.getByRole('button', { name: 'Submit' }).click();
// Avoid (fragile - CSS selectors)
await page.locator('#submit-btn').click();2. Explore Before Recording
Take snapshots to understand the page structure before recording actions:
playwright-cli open https://example.com
playwright-cli snapshot
# Review the element structure
playwright-cli click e53. Add Assertions Manually
Generated code captures actions but not assertions. Add expectations in your test:
// Generated action
await page.getByRole('button', { name: 'Submit' }).click();
// Manual assertion
await expect(page.getByText('Success')).toBeVisible();Tracing
Capture detailed execution traces for debugging and analysis. Traces include DOM snapshots, screenshots, network activity, and console logs.
Basic Usage
# Start trace recording
playwright-cli tracing-start
# Perform actions
playwright-cli open https://example.com
playwright-cli click e1
playwright-cli fill e2 "test"
# Stop trace recording
playwright-cli tracing-stopTrace Output Files
When you start tracing, Playwright creates a traces/ directory with several files:
trace-{timestamp}.trace
Action log - The main trace file containing:
- Every action performed (clicks, fills, navigations)
- DOM snapshots before and after each action
- Screenshots at each step
- Timing information
- Console messages
- Source locations
trace-{timestamp}.network
Network log - Complete network activity:
- All HTTP requests and responses
- Request headers and bodies
- Response headers and bodies
- Timing (DNS, connect, TLS, TTFB, download)
- Resource sizes
- Failed requests and errors
resources/
Resources directory - Cached resources:
- Images, fonts, stylesheets, scripts
- Response bodies for replay
- Assets needed to reconstruct page state
What Traces Capture
| Category | Details |
|---|---|
| Actions | Clicks, fills, hovers, keyboard input, navigations |
| DOM | Full DOM snapshot before/after each action |
| Screenshots | Visual state at each step |
| Network | All requests, responses, headers, bodies, timing |
| Console | All console.log, warn, error messages |
| Timing | Precise timing for each operation |
Use Cases
Debugging Failed Actions
playwright-cli tracing-start
playwright-cli open https://app.example.com
# This click fails - why?
playwright-cli click e5
playwright-cli tracing-stop
# Open trace to see DOM state when click was attemptedAnalyzing Performance
playwright-cli tracing-start
playwright-cli open https://slow-site.com
playwright-cli tracing-stop
# View network waterfall to identify slow resourcesCapturing Evidence
# Record a complete user flow for documentation
playwright-cli tracing-start
playwright-cli open https://app.example.com/checkout
playwright-cli fill e1 "4111111111111111"
playwright-cli fill e2 "12/25"
playwright-cli fill e3 "123"
playwright-cli click e4
playwright-cli tracing-stop
# Trace shows exact sequence of eventsTrace vs Video vs Screenshot
| Feature | Trace | Video | Screenshot |
|---|---|---|---|
| Format | .trace file | .webm video | .png/.jpeg image |
| DOM inspection | Yes | No | No |
| Network details | Yes | No | No |
| Step-by-step replay | Yes | Continuous | Single frame |
| File size | Medium | Large | Small |
| Best for | Debugging | Demos | Quick capture |
Best Practices
1. Start Tracing Before the Problem
# Trace the entire flow, not just the failing step
playwright-cli tracing-start
playwright-cli open https://example.com
# ... all steps leading to the issue ...
playwright-cli tracing-stop2. Clean Up Old Traces
Traces can consume significant disk space:
# Remove traces older than 7 days
find .playwright-cli/traces -mtime +7 -deleteLimitations
- Traces add overhead to automation
- Large traces can consume significant disk space
- Some dynamic content may not replay perfectly
Video Recording
Capture browser automation sessions as video for debugging, documentation, or verification. Produces WebM (VP8/VP9 codec).
Basic Recording
# Open browser first
playwright-cli open
# Start recording
playwright-cli video-start demo.webm
# Add a chapter marker for section transitions
playwright-cli video-chapter "Getting Started" --description="Opening the homepage" --duration=2000
# Navigate and perform actions
playwright-cli goto https://example.com
playwright-cli snapshot
playwright-cli click e1
# Add another chapter
playwright-cli video-chapter "Filling Form" --description="Entering test data" --duration=2000
playwright-cli fill e2 "test input"
# Stop and save
playwright-cli video-stopBest Practices
1. Use Descriptive Filenames
# Include context in filename
playwright-cli video-start recordings/login-flow-2024-01-15.webm
playwright-cli video-start recordings/checkout-test-run-42.webm2. Record entire hero scripts.
When recording a video for the user or as a proof of work, it is best to create a code snippet and execute it with run-code. It allows pulling appropriate pauses between the actions and annotating the video. There are new Playwright APIs for that.
1) Perform scenario using CLI and take note of all locators and actions. You'll need those locators to request their bounding boxes for highlight. 2) Create a file with the intended script for video (below). Use pressSequentially w/ delay for nice typing, make reasonable pauses. 3) Use playwright-cli run-code --filename your-script.js
Important: Overlays are pointer-events: none — they do not interfere with page interactions. You can safely keep sticky overlays visible while clicking, filling, or performing any actions on the page.
async page => {
await page.screencast.start({ path: 'video.webm', size: { width: 1280, height: 800 } });
await page.goto('https://demo.playwright.dev/todomvc');
// Show a chapter card — blurs the page and shows a dialog.
// Blocks until duration expires, then auto-removes.
// Use this for simple use cases, but always feel free to hand-craft your own beautiful
// overlay via await page.screencast.showOverlay().
await page.screencast.showChapter('Adding Todo Items', {
description: 'We will add several items to the todo list.',
duration: 2000,
});
// Perform action
await page.getByRole('textbox', { name: 'What needs to be done?' }).pressSequentially('Walk the dog', { delay: 60 });
await page.getByRole('textbox', { name: 'What needs to be done?' }).press('Enter');
await page.waitForTimeout(1000);
// Show next chapter
await page.screencast.showChapter('Verifying Results', {
description: 'Checking the item appeared in the list.',
duration: 2000,
});
// Add a sticky annotation that stays while you perform actions.
// Overlays are pointer-events: none, so they won't block clicks.
const annotation = await page.screencast.showOverlay(`
<div style="position: absolute; top: 8px; right: 8px;
padding: 6px 12px; background: rgba(0,0,0,0.7);
border-radius: 8px; font-size: 13px; color: white;">
✓ Item added successfully
</div>
`);
// Perform more actions while the annotation is visible
await page.getByRole('textbox', { name: 'What needs to be done?' }).pressSequentially('Buy groceries', { delay: 60 });
await page.getByRole('textbox', { name: 'What needs to be done?' }).press('Enter');
await page.waitForTimeout(1500);
// Remove the annotation when done
await annotation.dispose();
// You can also highlight relevant locators and provide contextual annotations.
const bounds = await page.getByText('Walk the dog').boundingBox();
await page.screencast.showOverlay(`
<div style="position: absolute;
top: ${bounds.y}px;
left: ${bounds.x}px;
width: ${bounds.width}px;
height: ${bounds.height}px;
border: 1px solid red;">
</div>
<div style="position: absolute;
top: ${bounds.y + bounds.height + 5}px;
left: ${bounds.x + bounds.width / 2}px;
transform: translateX(-50%);
padding: 6px;
background: #808080;
border-radius: 10px;
font-size: 14px;
color: white;">Check it out, it is right above this text
</div>
`, { duration: 2000 });
await page.screencast.stop();
}Embrace creativity, overlays are powerful.
Overlay API Summary
| Method | Use Case |
|---|---|
page.screencast.showChapter(title, { description?, duration?, styleSheet? }) | Full-screen chapter card with blurred backdrop — ideal for section transitions |
page.screencast.showOverlay(html, { duration? }) | Custom HTML overlay — use for callouts, labels, highlights |
disposable.dispose() | Remove a sticky overlay added without duration |
page.screencast.hideOverlays() / page.screencast.showOverlays() | Temporarily hide/show all overlays |
Tracing vs Video
| Feature | Video | Tracing |
|---|---|---|
| Output | WebM file | Trace file (viewable in Trace Viewer) |
| Shows | Visual recording | DOM snapshots, network, console, actions |
| Use case | Demos, documentation | Debugging, analysis |
| Size | Larger | Smaller |
Limitations
- Recording adds slight overhead to automation
- Large recordings can consume significant disk space
Related skills
FAQ
Can it generate tests?
Yes, it prints the Playwright code it ran so interactions can be converted into tests, and has a test-generation reference.
Can it attach to an existing browser?
Yes, via attach --cdp=chrome, --cdp=msedge, or a CDP endpoint like http://127.0.0.1:9222.