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

# BrowserManager

> Core class for managing Playwright browser instances and page interactions

# BrowserManager

The `BrowserManager` class manages the Playwright browser lifecycle with support for multiple tabs/windows, element refs, snapshots, and advanced browser automation features.

## Constructor

```typescript theme={null}
import { BrowserManager } from '@agentic-labs/browser';

const manager = new BrowserManager();
```

## Launch & Connection

### launch()

Launches a browser instance or connects to an existing one.

```typescript theme={null}
await manager.launch({
  headless: true,
  browser: 'chromium',
  viewport: { width: 1280, height: 720 }
});
```

<ParamField path="options" type="LaunchCommand">
  Launch configuration options

  <ParamField path="headless" type="boolean">
    Run browser in headless mode (default: true)
  </ParamField>

  <ParamField path="browser" type="'chromium' | 'firefox' | 'webkit'">
    Browser engine to launch (default: 'chromium')
  </ParamField>

  <ParamField path="viewport" type="{ width: number; height: number } | null">
    Initial viewport size. Set to null to disable viewport emulation
  </ParamField>

  <ParamField path="cdpPort" type="number">
    Connect to Chrome DevTools Protocol on this port
  </ParamField>

  <ParamField path="cdpUrl" type="string">
    Connect to CDP via WebSocket URL (ws\:// or wss\://)
  </ParamField>

  <ParamField path="autoConnect" type="boolean">
    Auto-discover and connect to running Chrome instance
  </ParamField>

  <ParamField path="provider" type="'browserbase' | 'browseruse' | 'kernel'">
    Cloud browser provider
  </ParamField>

  <ParamField path="extensions" type="string[]">
    Chrome extension paths to load (Chromium only)
  </ParamField>

  <ParamField path="profile" type="string">
    Path to persistent browser profile directory
  </ParamField>

  <ParamField path="storageState" type="string">
    Path to storage state JSON file for session persistence
  </ParamField>

  <ParamField path="proxy" type="object">
    Proxy configuration
    <ParamField path="server" type="string">Proxy server URL</ParamField>
    <ParamField path="username" type="string">Proxy authentication username</ParamField>
    <ParamField path="password" type="string">Proxy authentication password</ParamField>
  </ParamField>

  <ParamField path="headers" type="Record<string, string>">
    Extra HTTP headers to send with every request
  </ParamField>

  <ParamField path="userAgent" type="string">
    Custom user agent string
  </ParamField>

  <ParamField path="colorScheme" type="'light' | 'dark' | 'no-preference'">
    Persistent color scheme preference
  </ParamField>

  <ParamField path="downloadPath" type="string">
    Directory for browser downloads
  </ParamField>

  <ParamField path="allowedDomains" type="string[]">
    Domain allowlist for navigation (blocks other domains)
  </ParamField>

  <ParamField path="allowFileAccess" type="boolean">
    Enable file:// URL access (Chromium only)
  </ParamField>

  <ParamField path="ignoreHTTPSErrors" type="boolean">
    Ignore HTTPS certificate errors
  </ParamField>

  <ParamField path="args" type="string[]">
    Additional browser launch arguments
  </ParamField>
</ParamField>

### isLaunched()

Check if the browser is currently launched.

```typescript theme={null}
const launched = manager.isLaunched();
```

<ResponseField name="return" type="boolean">
  True if browser is launched
</ResponseField>

### close()

Close the browser and cleanup resources.

```typescript theme={null}
await manager.close();
```

## Page & Frame Management

### getPage()

Get the current active page. Throws if browser is not launched.

```typescript theme={null}
const page = manager.getPage();
```

<ResponseField name="return" type="Page">
  The active Playwright Page instance
</ResponseField>

### getPages()

Get all open pages.

```typescript theme={null}
const pages = manager.getPages();
```

<ResponseField name="return" type="Page[]">
  Array of all Page instances
</ResponseField>

### hasPages()

Check if the browser has any usable pages.

```typescript theme={null}
const hasPagesOpen = manager.hasPages();
```

<ResponseField name="return" type="boolean">
  True if pages exist
</ResponseField>

### ensurePage()

Ensure at least one page exists. Creates a new page if all were closed.

```typescript theme={null}
await manager.ensurePage();
```

### getFrame()

Get the current frame (or page's main frame if no frame is selected).

```typescript theme={null}
const frame = manager.getFrame();
```

<ResponseField name="return" type="Frame">
  Current Frame instance
</ResponseField>

### switchToFrame()

Switch to a frame by selector, name, or URL.

```typescript theme={null}
await manager.switchToFrame({ selector: 'iframe#myframe' });
await manager.switchToFrame({ name: 'payment' });
await manager.switchToFrame({ url: /checkout/ });
```

<ParamField path="options" type="object">
  <ParamField path="selector" type="string">CSS selector for frame element</ParamField>
  <ParamField path="name" type="string">Frame name attribute</ParamField>
  <ParamField path="url" type="string">Frame URL pattern</ParamField>
</ParamField>

### switchToMainFrame()

Switch back to the main frame.

```typescript theme={null}
manager.switchToMainFrame();
```

## Snapshots & Element Refs

### getSnapshot()

Get an enhanced accessibility snapshot with element refs.

```typescript theme={null}
const snapshot = await manager.getSnapshot({
  interactive: true,
  cursor: true,
  maxDepth: 5,
  compact: true
});

console.log(snapshot.tree);
console.log(snapshot.refs);
```

<ParamField path="options" type="object">
  <ParamField path="interactive" type="boolean">
    Only include interactive elements (buttons, links, inputs)
  </ParamField>

  <ParamField path="cursor" type="boolean">
    Include cursor-interactive elements (cursor:pointer, onclick)
  </ParamField>

  <ParamField path="maxDepth" type="number">
    Maximum depth of tree to include
  </ParamField>

  <ParamField path="compact" type="boolean">
    Remove structural elements without meaningful content
  </ParamField>

  <ParamField path="selector" type="string">
    CSS selector to scope the snapshot
  </ParamField>
</ParamField>

<ResponseField name="return" type="EnhancedSnapshot">
  <ResponseField name="tree" type="string">
    Accessibility tree as formatted text
  </ResponseField>

  <ResponseField name="refs" type="RefMap">
    Map of element refs to locator data
  </ResponseField>
</ResponseField>

### getRefMap()

Get the cached ref map from the last snapshot.

```typescript theme={null}
const refs = manager.getRefMap();
```

<ResponseField name="return" type="RefMap">
  Ref map with element locator information
</ResponseField>

### getLocatorFromRef()

Get a Playwright locator from a ref (e.g., "e1", "@e1", "ref=e1").

```typescript theme={null}
const locator = manager.getLocatorFromRef('@e5');
if (locator) {
  await locator.click();
}
```

<ParamField path="refArg" type="string">
  Element ref string (e1, @e1, or ref=e1)
</ParamField>

<ResponseField name="return" type="Locator | null">
  Playwright Locator or null if ref doesn't exist
</ResponseField>

### getLocator()

Get a locator - supports both refs and regular selectors.

```typescript theme={null}
const locator = manager.getLocator('@e3'); // by ref
const locator2 = manager.getLocator('#submit-button'); // by CSS
```

<ParamField path="selectorOrRef" type="string">
  Element ref or CSS selector
</ParamField>

<ResponseField name="return" type="Locator">
  Playwright Locator instance
</ResponseField>

### isRef()

Check if a selector looks like a ref.

```typescript theme={null}
const isElementRef = manager.isRef('@e1'); // true
const isCss = manager.isRef('.button'); // false
```

<ParamField path="selector" type="string">
  Selector string to check
</ParamField>

<ResponseField name="return" type="boolean">
  True if string is a ref format
</ResponseField>

### getLastSnapshot()

Get the last snapshot tree text (empty string if no snapshot has been taken).

```typescript theme={null}
const lastTree = manager.getLastSnapshot();
```

<ResponseField name="return" type="string">
  Last snapshot tree text
</ResponseField>

### setLastSnapshot()

Update the stored snapshot (used by diff to keep the baseline current).

```typescript theme={null}
manager.setLastSnapshot(newSnapshotTree);
```

<ParamField path="snapshot" type="string">
  Snapshot tree text to store
</ParamField>

## Browser Context & Settings

### getContext()

Get the current browser context.

```typescript theme={null}
const context = manager.getContext();
```

<ResponseField name="return" type="BrowserContext | null">
  Playwright BrowserContext or null
</ResponseField>

### getBrowser()

Get the current browser instance.

```typescript theme={null}
const browser = manager.getBrowser();
```

<ResponseField name="return" type="Browser | null">
  Playwright Browser instance or null
</ResponseField>

### getActiveIndex()

Get the current active page index.

```typescript theme={null}
const index = manager.getActiveIndex();
```

<ResponseField name="return" type="number">
  Zero-based index of active page
</ResponseField>

### setColorScheme()

Set the persistent color scheme preference. Applied to all new pages and contexts.

```typescript theme={null}
manager.setColorScheme('dark');
```

<ParamField path="scheme" type="'light' | 'dark' | 'no-preference' | null">
  Color scheme to apply
</ParamField>

### setViewport()

Set the viewport size.

```typescript theme={null}
await manager.setViewport(1920, 1080);
```

<ParamField path="width" type="number">
  Viewport width in pixels
</ParamField>

<ParamField path="height" type="number">
  Viewport height in pixels
</ParamField>

### setDeviceScaleFactor()

Set device scale factor (devicePixelRatio) via CDP.

```typescript theme={null}
await manager.setDeviceScaleFactor(2, 1920, 1080, false);
```

<ParamField path="deviceScaleFactor" type="number">
  Device pixel ratio (e.g., 2 for Retina)
</ParamField>

<ParamField path="width" type="number">
  Viewport width
</ParamField>

<ParamField path="height" type="number">
  Viewport height
</ParamField>

<ParamField path="mobile" type="boolean">
  Enable mobile emulation (default: false)
</ParamField>

### clearDeviceMetricsOverride()

Clear device metrics override to restore default devicePixelRatio.

```typescript theme={null}
await manager.clearDeviceMetricsOverride();
```

### getDevice()

Get device descriptor by name.

```typescript theme={null}
const device = manager.getDevice('iPhone 13 Pro');
```

<ParamField path="deviceName" type="string">
  Device name (e.g., "iPhone 13 Pro")
</ParamField>

<ResponseField name="return" type="DeviceDescriptor | undefined">
  Playwright device descriptor or undefined
</ResponseField>

### listDevices()

List all available device names.

```typescript theme={null}
const devices = manager.listDevices();
```

<ResponseField name="return" type="string[]">
  Array of device names
</ResponseField>

## Dialogs & Handlers

### setDialogHandler()

Set up automatic dialog (alert/confirm/prompt) handler.

```typescript theme={null}
manager.setDialogHandler('accept', 'My prompt text');
manager.setDialogHandler('dismiss');
```

<ParamField path="response" type="'accept' | 'dismiss'">
  How to respond to dialogs
</ParamField>

<ParamField path="promptText" type="string">
  Text to enter for prompt dialogs (when accepting)
</ParamField>

### clearDialogHandler()

Remove the dialog handler.

```typescript theme={null}
manager.clearDialogHandler();
```

## Request Tracking & Routing

### startRequestTracking()

Start tracking all network requests.

```typescript theme={null}
manager.startRequestTracking();
```

### getRequests()

Get tracked requests, optionally filtered.

```typescript theme={null}
const allRequests = manager.getRequests();
const apiRequests = manager.getRequests('/api/');
```

<ParamField path="filter" type="string">
  Optional URL substring filter
</ParamField>

<ResponseField name="return" type="TrackedRequest[]">
  Array of tracked request data
</ResponseField>

### clearRequests()

Clear all tracked requests.

```typescript theme={null}
manager.clearRequests();
```

### addRoute()

Add a route to intercept and mock requests.

```typescript theme={null}
await manager.addRoute('**/api/user', {
  response: {
    status: 200,
    body: JSON.stringify({ name: 'Test User' }),
    contentType: 'application/json'
  }
});

await manager.addRoute('**/analytics', { abort: true });
```

<ParamField path="url" type="string">
  URL pattern to intercept
</ParamField>

<ParamField path="options" type="object">
  <ParamField path="response" type="object">
    Mock response configuration
    <ParamField path="status" type="number">HTTP status code</ParamField>
    <ParamField path="body" type="string">Response body</ParamField>
    <ParamField path="contentType" type="string">Content-Type header</ParamField>
    <ParamField path="headers" type="Record<string, string>">Additional headers</ParamField>
  </ParamField>

  <ParamField path="abort" type="boolean">
    Abort the request instead of mocking
  </ParamField>
</ParamField>

### removeRoute()

Remove a route by URL pattern (or all routes if no URL provided).

```typescript theme={null}
await manager.removeRoute('**/api/user');
await manager.removeRoute(); // remove all
```

<ParamField path="url" type="string">
  Optional URL pattern to remove (omit to remove all)
</ParamField>

## Headers

### setExtraHeaders()

Set extra HTTP headers for all requests.

```typescript theme={null}
await manager.setExtraHeaders({
  'Authorization': 'Bearer token123',
  'X-Custom-Header': 'value'
});
```

<ParamField path="headers" type="Record<string, string>">
  Headers to set
</ParamField>

### setScopedHeaders()

Set headers only for requests matching an origin.

```typescript theme={null}
await manager.setScopedHeaders('api.example.com', {
  'Authorization': 'Bearer token123'
});
```

<ParamField path="origin" type="string">
  Origin hostname or URL
</ParamField>

<ParamField path="headers" type="Record<string, string>">
  Headers to add for matching requests
</ParamField>

### clearScopedHeaders()

Clear scoped headers for an origin (or all if no origin specified).

```typescript theme={null}
await manager.clearScopedHeaders('api.example.com');
await manager.clearScopedHeaders(); // clear all
```

<ParamField path="origin" type="string">
  Optional origin to clear (omit to clear all)
</ParamField>

## Geolocation & Permissions

### setGeolocation()

Set geolocation coordinates.

```typescript theme={null}
await manager.setGeolocation(37.7749, -122.4194, 100);
```

<ParamField path="latitude" type="number">
  Latitude coordinate
</ParamField>

<ParamField path="longitude" type="number">
  Longitude coordinate
</ParamField>

<ParamField path="accuracy" type="number">
  Optional accuracy in meters
</ParamField>

### setPermissions()

Grant or deny browser permissions.

```typescript theme={null}
await manager.setPermissions(['geolocation', 'notifications'], true);
await manager.setPermissions([], false); // revoke all
```

<ParamField path="permissions" type="string[]">
  Permission names to grant/deny
</ParamField>

<ParamField path="grant" type="boolean">
  True to grant, false to revoke
</ParamField>

### setOffline()

Set offline mode.

```typescript theme={null}
await manager.setOffline(true); // go offline
await manager.setOffline(false); // go online
```

<ParamField path="offline" type="boolean">
  Enable/disable offline mode
</ParamField>

## Console & Error Tracking

### startConsoleTracking()

Start tracking console messages.

```typescript theme={null}
manager.startConsoleTracking();
```

### getConsoleMessages()

Get all tracked console messages.

```typescript theme={null}
const messages = manager.getConsoleMessages();
```

<ResponseField name="return" type="ConsoleMessage[]">
  Array of console messages with type, text, and timestamp
</ResponseField>

### clearConsoleMessages()

Clear all tracked console messages.

```typescript theme={null}
manager.clearConsoleMessages();
```

### startErrorTracking()

Start tracking page errors.

```typescript theme={null}
manager.startErrorTracking();
```

### getPageErrors()

Get all tracked page errors.

```typescript theme={null}
const errors = manager.getPageErrors();
```

<ResponseField name="return" type="PageError[]">
  Array of page errors with message and timestamp
</ResponseField>

### clearPageErrors()

Clear all tracked page errors.

```typescript theme={null}
manager.clearPageErrors();
```

## Recording & Tracing

### startHarRecording()

Start HAR (HTTP Archive) recording.

```typescript theme={null}
await manager.startHarRecording();
```

### isHarRecording()

Check if HAR recording is active.

```typescript theme={null}
const recording = manager.isHarRecording();
```

<ResponseField name="return" type="boolean">
  True if recording
</ResponseField>

### startTracing()

Start Playwright tracing.

```typescript theme={null}
await manager.startTracing({
  screenshots: true,
  snapshots: true
});
```

<ParamField path="options" type="object">
  <ParamField path="screenshots" type="boolean">Include screenshots</ParamField>
  <ParamField path="snapshots" type="boolean">Include DOM snapshots</ParamField>
</ParamField>

### stopTracing()

Stop tracing and save to file.

```typescript theme={null}
await manager.stopTracing('./trace.zip');
```

<ParamField path="path" type="string">
  Optional output path for trace file
</ParamField>

## Storage State

### saveStorageState()

Save storage state (cookies, localStorage) to file.

```typescript theme={null}
await manager.saveStorageState('./state.json');
```

<ParamField path="path" type="string">
  Output file path
</ParamField>

### getAndClearWarnings()

Get and clear launch warnings (e.g., decryption failures).

```typescript theme={null}
const warnings = manager.getAndClearWarnings();
```

<ResponseField name="return" type="string[]">
  Array of warning messages
</ResponseField>

## Domain Filtering

### checkDomainAllowed()

Check if a URL is allowed by the domain allowlist. Throws if blocked.

```typescript theme={null}
try {
  manager.checkDomainAllowed('https://example.com');
} catch (error) {
  console.error('Domain blocked:', error.message);
}
```

<ParamField path="url" type="string">
  URL to check
</ParamField>

## Utility Functions

### getDefaultTimeout()

Get the default Playwright timeout in milliseconds.

```typescript theme={null}
import { getDefaultTimeout } from '@agentic-labs/browser';

const timeout = getDefaultTimeout(); // 25000 by default
```

<ResponseField name="return" type="number">
  Timeout in milliseconds (configurable via AGENT\_BROWSER\_DEFAULT\_TIMEOUT env var)
</ResponseField>

## TypeScript Types

```typescript theme={null}
import type {
  LaunchCommand,
  ScreencastFrame,
  ScreencastOptions,
  EnhancedSnapshot,
  RefMap
} from '@agentic-labs/browser';
```
