> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/microsoft/playwright-mcp/llms.txt
> Use this file to discover all available pages before exploring further.

# Browser Automation with Playwright

> Understanding how Playwright manages browsers, contexts, and pages

## 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:

<CardGroup cols={3}>
  <Card title="Chromium" icon="chrome">
    Google Chrome, Microsoft Edge, Brave, Opera
  </Card>

  <Card title="Firefox" icon="firefox">
    Mozilla Firefox
  </Card>

  <Card title="WebKit" icon="safari">
    Apple Safari
  </Card>
</CardGroup>

Specify the browser via configuration:

```json theme={null}
{
  "mcpServers": {
    "playwright": {
      "command": "npx",
      "args": [
        "@playwright/mcp@latest",
        "--browser=firefox"
      ]
    }
  }
}
```

Or use specific browser channels:

```bash theme={null}
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

```mermaid theme={null}
graph TB
    Browser[Browser Instance]
    Browser --> Context1[Context 1]
    Browser --> Context2[Context 2]
    Context1 --> Page1A[Page 1]
    Context1 --> Page1B[Page 2]
    Context2 --> Page2A[Page 1]
    
    style Context1 fill:#e1f5ff
    style Context2 fill:#fff4e1
```

Each context maintains:

* Independent cookies and sessions
* Separate localStorage and sessionStorage
* Isolated cache
* Individual permissions and geolocation

### Context Options

Configure context behavior through `contextOptions`:

```json theme={null}
{
  "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:

```bash theme={null}
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:

```typescript theme={null}
// 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 })
```

<Info>
  When you close the last tab in a context, the browser session ends and all state is lost (unless using persistent profile).
</Info>

## Headed vs Headless Modes

Playwright can run browsers in two modes:

<CardGroup cols={2}>
  <Card title="Headed (Default)" icon="window-maximize">
    **Visible browser window**

    ✓ See what's happening in real-time

    ✓ Easier debugging

    ✓ Better for development

    ✗ Requires display environment
  </Card>

  <Card title="Headless" icon="eye-slash">
    **No visible window**

    ✓ Runs on servers without display

    ✓ Faster execution

    ✓ Lower resource usage

    ✗ Can't visually inspect
  </Card>
</CardGroup>

### Enabling Headless Mode

```json theme={null}
{
  "mcpServers": {
    "playwright": {
      "command": "npx",
      "args": [
        "@playwright/mcp@latest",
        "--headless"
      ]
    }
  }
}
```

Or through configuration:

```json theme={null}
{
  "browser": {
    "launchOptions": {
      "headless": true
    }
  }
}
```

<Tip>
  Use headed mode during development to see what the AI agent is doing. Switch to headless for production deployments.
</Tip>

## 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:**

```bash theme={null}
# 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:**

```bash theme={null}
npx @playwright/mcp@latest --user-data-dir=/path/to/profile
```

### Isolated Profile

Browser profile is kept in memory and discarded after the session:

```json theme={null}
{
  "mcpServers": {
    "playwright": {
      "command": "npx",
      "args": [
        "@playwright/mcp@latest",
        "--isolated"
      ]
    }
  }
}
```

Or via configuration:

```json theme={null}
{
  "browser": {
    "isolated": true
  }
}
```

**Benefits:**

* Clean state for each session
* No profile pollution
* Ideal for testing
* Privacy-focused

**Provide initial state:**

```bash theme={null}
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.

<Note>
  Use persistent profiles for long-running automation tasks. Use isolated profiles for testing or when you need reproducible clean state.
</Note>

## Browser Extension Mode

Connect to an already-running browser instance using the Playwright MCP Bridge extension:

```bash theme={null}
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

<Info>
  Extension mode only works with Chrome and Edge browsers. See the extension installation guide for setup instructions.
</Info>

## CDP Connection

Connect to browsers using Chrome DevTools Protocol:

```json theme={null}
{
  "browser": {
    "cdpEndpoint": "http://localhost:9222",
    "cdpTimeout": 30000,
    "cdpHeaders": {
      "Authorization": "Bearer token"
    }
  }
}
```

Or via command-line:

```bash theme={null}
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:

```bash theme={null}
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

<CardGroup cols={3}>
  <Card title="iPhone 15" icon="mobile">
    393×852, iOS Safari
  </Card>

  <Card title="iPad Pro" icon="tablet">
    1024×1366, iOS Safari
  </Card>

  <Card title="Pixel 7" icon="android">
    412×915, Chrome Mobile
  </Card>
</CardGroup>

## Initialization Scripts

Inject custom JavaScript before pages load:

### Init Script (JavaScript)

Runs in every page before its scripts execute:

```javascript theme={null}
// init-script.js
window.isPlaywrightMCP = true;

Object.defineProperty(navigator, 'webdriver', {
  get: () => undefined
});
```

```bash theme={null}
npx @playwright/mcp@latest --init-script=./init-script.js
```

### Init Page (TypeScript)

Executes on the Playwright page object during setup:

```typescript theme={null}
// 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 });
};
```

```bash theme={null}
npx @playwright/mcp@latest --init-page=./init-page.ts
```

<Tip>
  Use `init-script` to modify browser APIs (e.g., bypass bot detection). Use `init-page` for Playwright API configuration (e.g., permissions, viewport).
</Tip>

## 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

```bash theme={null}
npx @playwright/mcp@latest \
  --save-trace \
  --output-dir=./traces
```

View traces with Playwright Trace Viewer:

```bash theme={null}
npx playwright show-trace trace.zip
```

### Video Recording

Record video of the browser session:

```bash theme={null}
npx @playwright/mcp@latest \
  --save-video=1280x720 \
  --output-dir=./recordings
```

### Session Logs

Save detailed session logs:

```bash theme={null}
npx @playwright/mcp@latest \
  --save-session \
  --output-mode=file \
  --output-dir=./logs
```

<Warning>
  Recording traces and videos increases resource usage and storage requirements. Only enable for debugging or important sessions.
</Warning>

## Next Steps

<CardGroup cols={2}>
  <Card title="Accessibility Snapshots" href="/concepts/accessibility-snapshots" icon="sitemap">
    Learn how Playwright captures page structure
  </Card>

  <Card title="Configuration Reference" href="/guides/configuration" icon="gear">
    Explore all configuration options
  </Card>
</CardGroup>
