Skip to main content
BrowserContext provides isolated sessions within a browser. Each context has its own cookies, cache, and storage.

Inheritance

Extends: ChannelOwner Implements: EventEmitter

Events

  • page: Emitted when a new page is created
  • close: Emitted when context is closed
  • request: Emitted when a request is made
  • response: Emitted when a response is received
  • requestfailed: Emitted when a request fails
  • requestfinished: Emitted when a request finishes
  • console: Emitted when console message is logged
  • dialog: Emitted when a dialog appears
  • weberror: Emitted when uncaught exception occurs
  • serviceworker: Emitted when service worker is created

Properties

request

request
APIRequestContext
API request context for making HTTP requests.

tracing

tracing
Tracing
Tracing instance for recording traces.

clock

clock
Clock
Clock instance for controlling time.

Methods

browser

Returns the browser that owns this context.
browser(): Browser | null
Returns: Browser | null - Parent browser or null for persistent contexts

pages

Returns all open pages in this context.
pages(): Page[]
Returns: Page[] - Array of pages

newPage

Creates a new page in this context.
newPage(): Promise<Page>
Returns: Promise<Page> - New page

cookies

Returns cookies.
cookies(urls?: string | string[]): Promise<Cookie[]>
urls
string | string[]
URL(s) to get cookies for. If not specified, returns all cookies.
Returns: Promise<Cookie[]> - Array of cookies

addCookies

Adds cookies to the context.
addCookies(cookies: Cookie[]): Promise<void>
cookies
Cookie[]
required
Array of cookie objects to addEach cookie should have:
  • name (string): Cookie name
  • value (string): Cookie value
  • url or domain (string): Cookie domain
  • path (string, optional): Cookie path
  • expires (number, optional): Expiration timestamp
  • httpOnly (boolean, optional): HTTP only flag
  • secure (boolean, optional): Secure flag
  • sameSite (‘Strict’ | ‘Lax’ | ‘None’, optional): SameSite attribute
Returns: Promise<void>

clearCookies

Clears cookies.
clearCookies(options?: ClearCookiesOptions): Promise<void>
options
ClearCookiesOptions
Cookie filter options
  • name (string | RegExp): Cookie name or pattern
  • domain (string | RegExp): Cookie domain or pattern
  • path (string | RegExp): Cookie path or pattern
Returns: Promise<void>

setDefaultNavigationTimeout

Sets default navigation timeout.
setDefaultNavigationTimeout(timeout: number): void
timeout
number
required
Timeout in milliseconds (0 to disable)

setDefaultTimeout

Sets default timeout for all operations.
setDefaultTimeout(timeout: number): void
timeout
number
required
Timeout in milliseconds (0 to disable)

grantPermissions

Grants specified permissions.
grantPermissions(permissions: string[], options?: { origin?: string }): Promise<void>
permissions
string[]
required
Permissions to grant (e.g., ‘geolocation’, ‘notifications’)
options
object
  • origin (string): Origin to grant permissions to
Returns: Promise<void>

clearPermissions

Clears all granted permissions.
clearPermissions(): Promise<void>
Returns: Promise<void>

setGeolocation

Sets geolocation.
setGeolocation(geolocation: { longitude: number, latitude: number, accuracy?: number } | null): Promise<void>
geolocation
object | null
required
Geolocation coordinates or null to clear
  • latitude (number): Latitude
  • longitude (number): Longitude
  • accuracy (number, optional): Accuracy in meters
Returns: Promise<void>

setExtraHTTPHeaders

Sets extra HTTP headers.
setExtraHTTPHeaders(headers: Headers): Promise<void>
headers
Headers
required
HTTP headers object
Returns: Promise<void>

setOffline

Sets offline mode.
setOffline(offline: boolean): Promise<void>
offline
boolean
required
Whether to enable offline mode
Returns: Promise<void>

setHTTPCredentials

Sets HTTP credentials for authentication.
setHTTPCredentials(httpCredentials: { username: string, password: string } | null): Promise<void>
httpCredentials
object | null
required
Credentials or null to clear
  • username (string): Username
  • password (string): Password
Returns: Promise<void>

addInitScript

Adds a script to evaluate in every page.
addInitScript(script: Function | string | { path?: string, content?: string }, arg?: any): Promise<void>
script
Function | string | object
required
Script to evaluate
arg
any
Argument to pass to the script
Returns: Promise<void>

exposeBinding

Exposes a binding.
exposeBinding(name: string, callback: Function, options?: { handle?: boolean }): Promise<void>
name
string
required
Binding name
callback
Function
required
Callback function
options
object
  • handle (boolean): Pass JSHandle instead of value
Returns: Promise<void>

exposeFunction

Exposes a function.
exposeFunction(name: string, callback: Function): Promise<void>
name
string
required
Function name
callback
Function
required
Function to expose
Returns: Promise<void>

route

Routes matching URLs to a handler.
route(url: string | RegExp, handler: Function, options?: { times?: number }): Promise<void>
url
string | RegExp
required
URL pattern to match
handler
Function
required
Route handler function
options
object
  • times (number): Maximum number of times to handle
Returns: Promise<void>

unroute

Removes a route.
unroute(url: string | RegExp, handler?: Function): Promise<void>
url
string | RegExp
required
URL pattern
handler
Function
Handler to remove (removes all if not specified)
Returns: Promise<void>

unrouteAll

Removes all routes.
unrouteAll(options?: { behavior?: 'wait' | 'ignoreErrors' | 'default' }): Promise<void>
options
object
  • behavior (string): How to handle pending routes
Returns: Promise<void>

routeFromHAR

Routes requests from a HAR file.
routeFromHAR(har: string, options?: RouteFromHAROptions): Promise<void>
har
string
required
Path to HAR file
options
RouteFromHAROptions
HAR routing options
  • url (string | RegExp): URL pattern to match
  • notFound (‘abort’ | ‘fallback’): Action when request not found
  • update (boolean): Update HAR file with new requests
Returns: Promise<void>

storageState

Returns storage state.
storageState(options?: { path?: string }): Promise<StorageState>
options
object
  • path (string): File path to save storage state to
Returns: Promise<StorageState> - Storage state object

waitForEvent

Waits for an event.
waitForEvent(event: string, optionsOrPredicate?: WaitForEventOptions | Function): Promise<any>
event
string
required
Event name
optionsOrPredicate
WaitForEventOptions | Function
Options or predicate function
Returns: Promise<any> - Event data

close

Closes the context.
close(options?: { reason?: string }): Promise<void>
options
object
  • reason (string): Close reason
Returns: Promise<void>

newCDPSession

Creates a CDP session.
newCDPSession(page: Page | Frame): Promise<CDPSession>
page
Page | Frame
required
Page or frame to attach to
Returns: Promise<CDPSession> - CDP session

serviceWorkers

Returns all service workers.
serviceWorkers(): Worker[]
Returns: Worker[] - Array of service workers

Usage Examples

Basic Context Usage

import { chromium } from 'playwright';

const browser = await chromium.launch();
const context = await browser.newContext({
  viewport: { width: 1280, height: 720 },
  userAgent: 'My User Agent',
});

const page = await context.newPage();
await page.goto('https://example.com');

await context.close();
await browser.close();
const context = await browser.newContext();

// Add cookies
await context.addCookies([
  {
    name: 'session',
    value: 'abc123',
    domain: 'example.com',
    path: '/',
  },
]);

// Get cookies
const cookies = await context.cookies();
console.log(cookies);

// Clear cookies
await context.clearCookies();

Request Interception

const context = await browser.newContext();

await context.route('**/*.{png,jpg,jpeg}', async (route) => {
  await route.abort();
});

await context.route('**/api/*', async (route) => {
  await route.fulfill({
    status: 200,
    body: JSON.stringify({ mocked: true }),
  });
});

const page = await context.newPage();

Storage State Persistence

// Save storage state
const context = await browser.newContext();
const page = await context.newPage();
await page.goto('https://example.com');
// ... perform login ...
await context.storageState({ path: 'state.json' });
await context.close();

// Restore storage state
const newContext = await browser.newContext({
  storageState: 'state.json',
});
const newPage = await newContext.newPage();
// User is logged in

Build docs developers (and LLMs) love