Skip to main content

How Playwright Works

Playwright is a browser automation framework that controls real browsers (Chromium, Firefox, WebKit) through their respective DevTools protocols. Unlike screenshot-based approaches, Playwright interacts with the browser’s internal APIs to perform actions precisely as a user would.

Browser Engines

Playwright MCP supports three browser engines:

Chromium

Google Chrome, Microsoft Edge, Brave, Opera

Firefox

Mozilla Firefox

WebKit

Apple Safari
Specify the browser via configuration:
{
  "mcpServers": {
    "playwright": {
      "command": "npx",
      "args": [
        "@playwright/mcp@latest",
        "--browser=firefox"
      ]
    }
  }
}
Or use specific browser channels:
npx @playwright/mcp@latest --browser=msedge

Browser Contexts

A browser context is an isolated browser session with its own cookies, localStorage, and cache. Think of it as an incognito window.

Context Isolation

Each context maintains:
  • Independent cookies and sessions
  • Separate localStorage and sessionStorage
  • Isolated cache
  • Individual permissions and geolocation

Context Options

Configure context behavior through contextOptions:
{
  "browser": {
    "contextOptions": {
      "viewport": {
        "width": 1280,
        "height": 720
      },
      "userAgent": "Custom User Agent",
      "permissions": ["geolocation", "clipboard-read"],
      "geolocation": {
        "latitude": 37.7749,
        "longitude": -122.4194
      }
    }
  }
}
Or via command-line:
npx @playwright/mcp@latest \
  --viewport-size=1280x720 \
  --grant-permissions=geolocation,clipboard-read

Pages and Tabs

A page represents a single browser tab within a context. Playwright MCP provides tab management tools:
// List all tabs
browser_tabs({ action: "list" })

// Create new tab
browser_tabs({ action: "new" })

// Switch to tab by index
browser_tabs({ action: "select", index: 1 })

// Close tab
browser_tabs({ action: "close", index: 2 })
When you close the last tab in a context, the browser session ends and all state is lost (unless using persistent profile).

Headed vs Headless Modes

Playwright can run browsers in two modes:

Headed (Default)

Visible browser window✓ See what’s happening in real-time✓ Easier debugging✓ Better for development✗ Requires display environment

Headless

No visible window✓ Runs on servers without display✓ Faster execution✓ Lower resource usage✗ Can’t visually inspect

Enabling Headless Mode

{
  "mcpServers": {
    "playwright": {
      "command": "npx",
      "args": [
        "@playwright/mcp@latest",
        "--headless"
      ]
    }
  }
}
Or through configuration:
{
  "browser": {
    "launchOptions": {
      "headless": true
    }
  }
}
Use headed mode during development to see what the AI agent is doing. Switch to headless for production deployments.

Persistent vs Isolated Profiles

Playwright MCP supports two profile management strategies:

Persistent Profile (Default)

Browser data is saved to disk and persists between sessions: Storage locations:
# Windows
%USERPROFILE%\AppData\Local\ms-playwright\mcp-{channel}-profile

# macOS
~/Library/Caches/ms-playwright/mcp-{channel}-profile

# Linux
~/.cache/ms-playwright/mcp-{channel}-profile
Benefits:
  • Logged-in sessions persist
  • Cookies and localStorage remain
  • Browser settings saved
  • History and bookmarks preserved
Use custom profile location:
npx @playwright/mcp@latest --user-data-dir=/path/to/profile

Isolated Profile

Browser profile is kept in memory and discarded after the session:
{
  "mcpServers": {
    "playwright": {
      "command": "npx",
      "args": [
        "@playwright/mcp@latest",
        "--isolated"
      ]
    }
  }
}
Or via configuration:
{
  "browser": {
    "isolated": true
  }
}
Benefits:
  • Clean state for each session
  • No profile pollution
  • Ideal for testing
  • Privacy-focused
Provide initial state:
npx @playwright/mcp@latest \
  --isolated \
  --storage-state=./auth-state.json
The storage-state file contains cookies and localStorage that will be loaded into the isolated context.
Use persistent profiles for long-running automation tasks. Use isolated profiles for testing or when you need reproducible clean state.

Browser Extension Mode

Connect to an already-running browser instance using the Playwright MCP Bridge extension:
npx @playwright/mcp@latest --extension
This mode allows you to:
  • Use your existing logged-in sessions
  • Access browser profiles with extensions
  • Leverage bookmarks and history
  • Work with enterprise browser configurations
Extension mode only works with Chrome and Edge browsers. See the extension installation guide for setup instructions.

CDP Connection

Connect to browsers using Chrome DevTools Protocol:
{
  "browser": {
    "cdpEndpoint": "http://localhost:9222",
    "cdpTimeout": 30000,
    "cdpHeaders": {
      "Authorization": "Bearer token"
    }
  }
}
Or via command-line:
npx @playwright/mcp@latest \
  --cdp-endpoint=http://localhost:9222 \
  --cdp-timeout=30000
Use cases:
  • Connect to remote browser instances
  • Use cloud browser services
  • Debug running applications
  • Enterprise browser management

Device Emulation

Emulate mobile devices and tablets:
npx @playwright/mcp@latest --device="iPhone 15"
This automatically configures:
  • Screen size and pixel ratio
  • User agent string
  • Touch event support
  • Mobile viewport meta tag

iPhone 15

393×852, iOS Safari

iPad Pro

1024×1366, iOS Safari

Pixel 7

412×915, Chrome Mobile

Initialization Scripts

Inject custom JavaScript before pages load:

Init Script (JavaScript)

Runs in every page before its scripts execute:
// init-script.js
window.isPlaywrightMCP = true;

Object.defineProperty(navigator, 'webdriver', {
  get: () => undefined
});
npx @playwright/mcp@latest --init-script=./init-script.js

Init Page (TypeScript)

Executes on the Playwright page object during setup:
// init-page.ts
export default async ({ page }) => {
  await page.context().grantPermissions(['geolocation']);
  await page.context().setGeolocation({ 
    latitude: 37.7749, 
    longitude: -122.4194 
  });
  await page.setViewportSize({ width: 1280, height: 720 });
};
npx @playwright/mcp@latest --init-page=./init-page.ts
Use init-script to modify browser APIs (e.g., bypass bot detection). Use init-page for Playwright API configuration (e.g., permissions, viewport).

Session Recording

Capture browser sessions for debugging and analysis:

Trace Recording

Playwright traces include:
  • DOM snapshots at each step
  • Network requests and responses
  • Console messages
  • Screenshots
  • Action timeline
npx @playwright/mcp@latest \
  --save-trace \
  --output-dir=./traces
View traces with Playwright Trace Viewer:
npx playwright show-trace trace.zip

Video Recording

Record video of the browser session:
npx @playwright/mcp@latest \
  --save-video=1280x720 \
  --output-dir=./recordings

Session Logs

Save detailed session logs:
npx @playwright/mcp@latest \
  --save-session \
  --output-mode=file \
  --output-dir=./logs
Recording traces and videos increases resource usage and storage requirements. Only enable for debugging or important sessions.

Next Steps

Accessibility Snapshots

Learn how Playwright captures page structure

Configuration Reference

Explore all configuration options