Skip to main content

BrowserManager

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

Constructor

Launch & Connection

launch()

Launches a browser instance or connects to an existing one.
LaunchCommand
Launch configuration options
boolean
Run browser in headless mode (default: true)
'chromium' | 'firefox' | 'webkit'
Browser engine to launch (default: ‘chromium’)
{ width: number; height: number } | null
Initial viewport size. Set to null to disable viewport emulation
number
Connect to Chrome DevTools Protocol on this port
string
Connect to CDP via WebSocket URL (ws:// or wss://)
boolean
Auto-discover and connect to running Chrome instance
'browserbase' | 'browseruse' | 'kernel'
Cloud browser provider
string[]
Chrome extension paths to load (Chromium only)
string
Path to persistent browser profile directory
string
Path to storage state JSON file for session persistence
object
Proxy configuration
string
Proxy server URL
string
Proxy authentication username
string
Proxy authentication password
Record<string, string>
Extra HTTP headers to send with every request
string
Custom user agent string
'light' | 'dark' | 'no-preference'
Persistent color scheme preference
string
Directory for browser downloads
string[]
Domain allowlist for navigation (blocks other domains)
boolean
Enable file:// URL access (Chromium only)
boolean
Ignore HTTPS certificate errors
string[]
Additional browser launch arguments

isLaunched()

Check if the browser is currently launched.
boolean
True if browser is launched

close()

Close the browser and cleanup resources.

Page & Frame Management

getPage()

Get the current active page. Throws if browser is not launched.
Page
The active Playwright Page instance

getPages()

Get all open pages.
Page[]
Array of all Page instances

hasPages()

Check if the browser has any usable pages.
boolean
True if pages exist

ensurePage()

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

getFrame()

Get the current frame (or page’s main frame if no frame is selected).
Frame
Current Frame instance

switchToFrame()

Switch to a frame by selector, name, or URL.
object
string
CSS selector for frame element
string
Frame name attribute
string
Frame URL pattern

switchToMainFrame()

Switch back to the main frame.

Snapshots & Element Refs

getSnapshot()

Get an enhanced accessibility snapshot with element refs.
object
boolean
Only include interactive elements (buttons, links, inputs)
boolean
Include cursor-interactive elements (cursor:pointer, onclick)
number
Maximum depth of tree to include
boolean
Remove structural elements without meaningful content
string
CSS selector to scope the snapshot
EnhancedSnapshot
string
Accessibility tree as formatted text
RefMap
Map of element refs to locator data

getRefMap()

Get the cached ref map from the last snapshot.
RefMap
Ref map with element locator information

getLocatorFromRef()

Get a Playwright locator from a ref (e.g., “e1”, “@e1”, “ref=e1”).
string
Element ref string (e1, @e1, or ref=e1)
Locator | null
Playwright Locator or null if ref doesn’t exist

getLocator()

Get a locator - supports both refs and regular selectors.
string
Element ref or CSS selector
Locator
Playwright Locator instance

isRef()

Check if a selector looks like a ref.
string
Selector string to check
boolean
True if string is a ref format

getLastSnapshot()

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

setLastSnapshot()

Update the stored snapshot (used by diff to keep the baseline current).
string
Snapshot tree text to store

Browser Context & Settings

getContext()

Get the current browser context.
BrowserContext | null
Playwright BrowserContext or null

getBrowser()

Get the current browser instance.
Browser | null
Playwright Browser instance or null

getActiveIndex()

Get the current active page index.
number
Zero-based index of active page

setColorScheme()

Set the persistent color scheme preference. Applied to all new pages and contexts.
'light' | 'dark' | 'no-preference' | null
Color scheme to apply

setViewport()

Set the viewport size.
number
Viewport width in pixels
number
Viewport height in pixels

setDeviceScaleFactor()

Set device scale factor (devicePixelRatio) via CDP.
number
Device pixel ratio (e.g., 2 for Retina)
number
Viewport width
number
Viewport height
boolean
Enable mobile emulation (default: false)

clearDeviceMetricsOverride()

Clear device metrics override to restore default devicePixelRatio.

getDevice()

Get device descriptor by name.
string
Device name (e.g., “iPhone 13 Pro”)
DeviceDescriptor | undefined
Playwright device descriptor or undefined

listDevices()

List all available device names.
string[]
Array of device names

Dialogs & Handlers

setDialogHandler()

Set up automatic dialog (alert/confirm/prompt) handler.
'accept' | 'dismiss'
How to respond to dialogs
string
Text to enter for prompt dialogs (when accepting)

clearDialogHandler()

Remove the dialog handler.

Request Tracking & Routing

startRequestTracking()

Start tracking all network requests.

getRequests()

Get tracked requests, optionally filtered.
string
Optional URL substring filter
TrackedRequest[]
Array of tracked request data

clearRequests()

Clear all tracked requests.

addRoute()

Add a route to intercept and mock requests.
string
URL pattern to intercept
object
object
Mock response configuration
number
HTTP status code
string
Response body
string
Content-Type header
Record<string, string>
Additional headers
boolean
Abort the request instead of mocking

removeRoute()

Remove a route by URL pattern (or all routes if no URL provided).
string
Optional URL pattern to remove (omit to remove all)

Headers

setExtraHeaders()

Set extra HTTP headers for all requests.
Record<string, string>
Headers to set

setScopedHeaders()

Set headers only for requests matching an origin.
string
Origin hostname or URL
Record<string, string>
Headers to add for matching requests

clearScopedHeaders()

Clear scoped headers for an origin (or all if no origin specified).
string
Optional origin to clear (omit to clear all)

Geolocation & Permissions

setGeolocation()

Set geolocation coordinates.
number
Latitude coordinate
number
Longitude coordinate
number
Optional accuracy in meters

setPermissions()

Grant or deny browser permissions.
string[]
Permission names to grant/deny
boolean
True to grant, false to revoke

setOffline()

Set offline mode.
boolean
Enable/disable offline mode

Console & Error Tracking

startConsoleTracking()

Start tracking console messages.

getConsoleMessages()

Get all tracked console messages.
ConsoleMessage[]
Array of console messages with type, text, and timestamp

clearConsoleMessages()

Clear all tracked console messages.

startErrorTracking()

Start tracking page errors.

getPageErrors()

Get all tracked page errors.
PageError[]
Array of page errors with message and timestamp

clearPageErrors()

Clear all tracked page errors.

Recording & Tracing

startHarRecording()

Start HAR (HTTP Archive) recording.

isHarRecording()

Check if HAR recording is active.
boolean
True if recording

startTracing()

Start Playwright tracing.
object
boolean
Include screenshots
boolean
Include DOM snapshots

stopTracing()

Stop tracing and save to file.
string
Optional output path for trace file

Storage State

saveStorageState()

Save storage state (cookies, localStorage) to file.
string
Output file path

getAndClearWarnings()

Get and clear launch warnings (e.g., decryption failures).
string[]
Array of warning messages

Domain Filtering

checkDomainAllowed()

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

Utility Functions

getDefaultTimeout()

Get the default Playwright timeout in milliseconds.
number
Timeout in milliseconds (configurable via AGENT_BROWSER_DEFAULT_TIMEOUT env var)

TypeScript Types