Skip to main content

What is a Browser Context?

A BrowserContext (client/browserContext.ts:58) is an isolated, incognito-like browser session within a browser instance. Each context has:
  • Independent cookies
  • Separate localStorage and sessionStorage
  • Isolated cache
  • Independent permissions and geolocation
  • Separate network state
Think of contexts as separate browser profiles running in the same browser process.

Creating Contexts

Basic Context Creation

Context with Options

BrowserContext Class

From client/browserContext.ts:58-174:

Context Lifecycle

1

Create Context

2

Create Pages

3

Configure Context

4

Use Pages

All pages share the context’s state
5

Close Context

All pages in the context are closed

Context Isolation

Contexts are completely isolated from each other:

Cookies Management

Getting Cookies

From client/browserContext.ts:301:

Adding Cookies

Clearing Cookies

Storage State

Saving State

Save cookies and localStorage for later reuse:

Loading State

Restore saved state in a new context:
From client/browserContext.ts:465:

Permissions

Granting Permissions

Clearing Permissions

Available permissions:
  • geolocation
  • notifications
  • camera
  • microphone
  • clipboard-read
  • clipboard-write

Network Control

HTTP Credentials

Extra HTTP Headers

Offline Mode

Route Handlers

Intercept and modify network requests at the context level:
From client/browserContext.ts:368-371:

Events

Tracing

Record traces for debugging:

API Request Context

Each context has an API request context for HTTP requests:
From client/browserContext.ts:97:

Emulation

Viewport

User Agent

Locale and Timezone

Color Scheme

Best Practices

Create a fresh context for each test to ensure isolation.
Contexts are lightweight but should be recreated for test isolation.
Authenticate once, save state, reuse across tests.

Next Steps

Pages and Frames

Working with pages within contexts

Test Isolation

Ensuring test independence

Selectors

Finding elements on pages