Playwright CLI

repository·main·Indexed 11 days ago

https://github.com/microsoft/playwright-cli

A command-line interface for Playwright version 0.1.18 designed for high-throughput coding agents. It provides token-efficient SKILLs as an alternative to MCP to automate browsers without overwhelming LLM context windows. Features include session management, a visual dashboard for monitoring, headless and headed modes, and a JSON configuration schema for browser and network settings.

Tokens
22.2K
Snippets
67
Records
76
Agent score
92%

What's inside Playwright CLI

  1. Advanced Playwright automation tasks

    main

    For more complex automation scenarios, refer to the following specialized guides:

    • Running and Debugging Playwright tests: Guidance on executing and troubleshooting test suites.
    • Request mocking: How to intercept and mock network requests.
    • Running Playwright code: Executing custom Playwright scripts.
    • Browser session management: Managing active browser sessions.
    • Storage state: Handling cookies and localStorage.
    • Test generation: Using plan, generate, and heal workflows.
    • Observability: Using Tracing and Video recording to inspect execution.
    • Inspection: Inspecting specific element attributes.
  2. Manage isolated browser sessions with named sessions

    main

    You can run multiple isolated browser sessions concurrently using the -s (or --session) flag. Each session maintains its own independent state, including:

    • Cookies
    • LocalStorage / SessionStorage
    • IndexedDB
    • Cache
    • Browsing history
    • Open tabs

    Use the -s flag to assign a name to a session, allowing you to run different workflows (e.g., an authenticated session and a public session) without them interfering with each other.

    # 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 snapshot
  3. Security best practices for storage state files

    main

    When managing storage state files (e.g., .json files containing auth tokens):

    • Never commit these files to version control.
    • Add patterns like *.auth-state.json to your .gitignore.
    • Delete state files immediately after automation completes.
    • Use environment variables for sensitive data instead of hardcoding them in scripts.
    • In-memory mode: By default, sessions run in-memory mode, which is safer for sensitive operations.
  4. Target elements using selectors and refs

    main

    You can target elements in three ways:

    1. Snapshot Refs: Use the short identifiers (e.g., e15) generated in the snapshot output.
    2. CSS Selectors: Use standard CSS syntax (e.g., #main > button.submit).
    3. Playwright Locators: Use Playwright's locator API strings (e.g., getByRole('button', { name: 'Submit' }) or getByTestId('submit-button')).
    # Using a ref
    playwright-cli click e5
    
    # Using CSS
    playwright-cli click "#main > button.submit"
    
    # Using Playwright locators
    playwright-cli click "getByRole('button', { name: 'Submit' })"
    playwright-cli click "getByTestId('submit-button')"
    playwright-cli click e5
    playwright-cli click "#main > button.submit"
    playwright-cli click "getByRole('button', { name: 'Submit' })"
    playwright-cli click "getByTestId('submit-button')"
  5. Use snapshots to identify and interact with elements

    main

    After every command, playwright-cli provides a snapshot of the current browser state. You can use these snapshots to obtain element references (ref) for subsequent commands.

    Taking Snapshots

    You can take snapshots on demand using the snapshot command. Options include:

    • --filename=<file>: Save to a specific file.
    • <ref>: Snapshot a specific element instead of the whole page.
    • --depth=<N>: Limit snapshot depth for efficiency.
    • --boxes: Include each element's bounding box as [box=x,y,width,height].

    Searching Snapshots

    Use find to search the snapshot for text or patterns:

    • playwright-cli find "text": Returns matching nodes with context.
    • playwright-cli find --regex "pattern": Search using a regular expression. For flags like case-insensitivity, wrap the pattern in slashes (e.g., /pattern/i).

    Interacting with Elements

    By default, use the ref IDs provided in the snapshot. You can also use CSS selectors or Playwright locators directly.

    playwright-cli snapshot
    playwright-cli click e15
    
    # Using CSS selectors
    playwright-cli click "#main > button.submit"
    
    # Using Playwright locators
    playwright-cli click "getByRole('button', { name: 'Submit' })"
    playwright-cli click "getByTestId('submit-button')"
  6. Understand trace output files and structure

    main

    When tracing is active, playwright-cli creates a traces/ directory containing the following components:

    • trace-{timestamp}.trace: The main Action log. It contains every action performed (clicks, fills, navigations), DOM snapshots before and after each action, screenshots at each step, timing information, console messages, and source locations.
    • trace-{timestamp}.network: The Network log. It contains complete network activity, including all HTTP requests/responses, headers, bodies, timing (DNS, connect, TLS, TTFB, download), resource sizes, and failed requests.
    • resources/: A directory of cached resources (images, fonts, stylesheets, scripts) and response bodies required to reconstruct and replay the page state.
  7. Manage browser sessions and persistence

    main

    Playwright CLI manages browser state through sessions.

    State Persistence

    • In-memory (Default): Cookies and storage state are preserved between CLI calls within a single session but are lost when the browser closes.
    • Disk Persistence: Use the --persistent flag to save the profile to disk, allowing state to persist across browser restarts.

    Session Isolation

    Use the -s= flag to assign a specific session name to an invocation. This allows you to run different browser instances for different projects simultaneously.

    Session Management Commands

    • playwright-cli list: List all active sessions.
    • playwright-cli close-all: Close all running browsers.
    • playwright-cli kill-all: Forcefully kill all browser processes.

    Environment Variable

    To run a coding agent within a specific session, set the PLAYWRIGHT_CLI_SESSION environment variable.

    # Open a specific session and persist it to disk
    playwright-cli -s=example open https://example.com --persistent
    
    # Run an agent in a specific session
    PLAYWRIGHT_CLI_SESSION=todo-app claude .
  8. Capture and search snapshots

    main

    A snapshot provides a representation of the current browser state. You can take snapshots on demand or use the ones generated automatically after commands.

    Taking Snapshots

    • snapshot: Saves a snapshot with a timestamped name.
    • snapshot --filename=<name>: Saves to a specific file.
    • snapshot <selector|ref>: Snapshots a specific element.
    • snapshot --depth=<n>: Limits snapshot depth for efficiency.
    • snapshot --boxes: Includes element bounding boxes in the snapshot.

    Searching Snapshots

    Use the find command to search within a snapshot for text or regular expressions. It returns matching nodes with surrounding context.

    playwright-cli find "Add to cart"
    playwright-cli find --regex "\$[0-9]+\.[0-9]{2}"
    playwright-cli find --regex "/sign (in|up)/i"
    playwright-cli snapshot --filename=after-click.yaml
    playwright-cli snapshot "#main"
    playwright-cli snapshot e34 --boxes
    playwright-cli find "Sign in"
  9. How test generation works with playwright-cli

    main

    The playwright-cli provides an end-to-end workflow for authoring and maintaining Playwright tests using a Plan → Generate → Heal model.

    Every action performed via the CLI (like click or fill) automatically generates the equivalent Playwright TypeScript code. This generated code is intended to be copied directly into your test files.

    Core Workflow Components:

    • Plan: Explore the application and produce a specification file (e.g., specs/<feature>.plan.md) describing what to test.
    • Generate: Convert a specification file into actual Playwright test files.
    • Heal: Diagnose failing tests, fix the code, and reconcile the specification with the current state of the application.

    To drive the interactive session, you must run npx playwright test --debug=cli in the background and then use playwright-cli attach <session-id> to connect.

    # 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 click e3
    # Ran Playwright code:
    # await page.getByRole('button', { name: 'Sign In' }).click();
  10. Emulate Media and Color Schemes

    main

    Use page.emulateMedia() to test how your application responds to different media queries and user preferences.

    # 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' });
    }"