or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

advanced-features.mdapi-testing.mdassertions.mdbrowser-management.mdelement-location.mdindex.mdmobile-testing.mdnetwork-interception.mdpage-interaction.md

browser-management.mddocs/

0

# Browser Management

1

2

Comprehensive browser lifecycle management including launching browser instances, creating isolated contexts, and managing browser configurations across Chromium, Firefox, and WebKit.

3

4

## Capabilities

5

6

### Entry Points

7

8

Launch Playwright and get access to browser types.

9

10

```python { .api }

11

def sync_playwright() -> PlaywrightContextManager:

12

"""

13

Returns synchronous Playwright context manager.

14

15

Returns:

16

PlaywrightContextManager: Context manager for browser automation

17

"""

18

19

def async_playwright() -> PlaywrightContextManager:

20

"""

21

Returns asynchronous Playwright context manager.

22

23

Returns:

24

PlaywrightContextManager: Async context manager for browser automation

25

"""

26

27

class PlaywrightContextManager:

28

def __enter__(self) -> Playwright: ...

29

def __exit__(self, *args) -> None: ...

30

async def __aenter__(self) -> Playwright: ...

31

async def __aexit__(self, *args) -> None: ...

32

```

33

34

### Browser Type Management

35

36

Access to different browser engines with launch capabilities.

37

38

```python { .api }

39

class Playwright:

40

"""Main Playwright interface providing access to browser types."""

41

chromium: BrowserType

42

firefox: BrowserType

43

webkit: BrowserType

44

devices: Dict[str, Dict[str, Any]]

45

selectors: Selectors

46

request: APIRequest

47

48

class BrowserType:

49

"""Represents a browser engine (Chromium, Firefox, WebKit)."""

50

name: str

51

executable_path: str

52

53

def launch(

54

self,

55

executable_path: Optional[str] = None,

56

channel: Optional[str] = None,

57

args: Optional[List[str]] = None,

58

ignore_default_args: Union[bool, List[str], None] = None,

59

handle_sigint: Optional[bool] = None,

60

handle_sigterm: Optional[bool] = None,

61

handle_sighup: Optional[bool] = None,

62

timeout: Optional[float] = None,

63

env: Optional[Dict[str, Union[str, int, bool]]] = None,

64

headless: Optional[bool] = None,

65

devtools: Optional[bool] = None,

66

proxy: Optional[ProxySettings] = None,

67

downloads_path: Optional[str] = None,

68

slow_mo: Optional[float] = None,

69

traces_dir: Optional[str] = None,

70

chromium_sandbox: Optional[bool] = None,

71

firefox_user_prefs: Optional[Dict[str, Any]] = None

72

) -> Browser:

73

"""

74

Launch new browser instance.

75

76

Args:

77

executable_path: Path to browser executable

78

channel: Browser channel (chrome, chrome-beta, msedge, etc.)

79

args: Additional command line arguments

80

ignore_default_args: Skip default arguments

81

handle_sigint: Handle SIGINT signal

82

handle_sigterm: Handle SIGTERM signal

83

handle_sighup: Handle SIGHUP signal

84

timeout: Launch timeout in milliseconds

85

env: Environment variables

86

headless: Run in headless mode

87

devtools: Open devtools

88

proxy: Proxy configuration

89

downloads_path: Download directory

90

slow_mo: Slow down operations by milliseconds

91

traces_dir: Directory for traces

92

chromium_sandbox: Enable/disable sandbox (Chromium only)

93

firefox_user_prefs: Firefox preferences

94

95

Returns:

96

Browser: New browser instance

97

"""

98

99

def launch_persistent_context(

100

self,

101

user_data_dir: str,

102

executable_path: Optional[str] = None,

103

channel: Optional[str] = None,

104

args: Optional[List[str]] = None,

105

ignore_default_args: Union[bool, List[str], None] = None,

106

handle_sigint: Optional[bool] = None,

107

handle_sigterm: Optional[bool] = None,

108

handle_sighup: Optional[bool] = None,

109

timeout: Optional[float] = None,

110

env: Optional[Dict[str, Union[str, int, bool]]] = None,

111

headless: Optional[bool] = None,

112

devtools: Optional[bool] = None,

113

proxy: Optional[ProxySettings] = None,

114

downloads_path: Optional[str] = None,

115

slow_mo: Optional[float] = None,

116

traces_dir: Optional[str] = None,

117

chromium_sandbox: Optional[bool] = None,

118

firefox_user_prefs: Optional[Dict[str, Any]] = None,

119

viewport: Optional[ViewportSize] = None,

120

screen: Optional[Dict] = None,

121

no_viewport: Optional[bool] = None,

122

ignore_https_errors: Optional[bool] = None,

123

java_script_enabled: Optional[bool] = None,

124

bypass_csp: Optional[bool] = None,

125

user_agent: Optional[str] = None,

126

locale: Optional[str] = None,

127

timezone_id: Optional[str] = None,

128

geolocation: Optional[Geolocation] = None,

129

permissions: Optional[List[str]] = None,

130

extra_http_headers: Optional[Dict[str, str]] = None,

131

offline: Optional[bool] = None,

132

http_credentials: Optional[HttpCredentials] = None,

133

device_scale_factor: Optional[float] = None,

134

is_mobile: Optional[bool] = None,

135

has_touch: Optional[bool] = None,

136

color_scheme: Optional[str] = None,

137

reduced_motion: Optional[str] = None,

138

forced_colors: Optional[str] = None,

139

accept_downloads: Optional[bool] = None,

140

record_har_path: Optional[str] = None,

141

record_har_omit_content: Optional[bool] = None,

142

record_video_dir: Optional[str] = None,

143

record_video_size: Optional[ViewportSize] = None,

144

storage_state: Union[str, StorageState, None] = None,

145

base_url: Optional[str] = None,

146

strict_selectors: Optional[bool] = None,

147

service_workers: Optional[str] = None,

148

record_har_url_filter: Union[str, Pattern, None] = None,

149

record_har_mode: Optional[str] = None,

150

record_har_content: Optional[str] = None

151

) -> BrowserContext:

152

"""

153

Launch browser instance with persistent user data directory.

154

155

Args:

156

user_data_dir: Directory for persistent user data

157

(other args same as launch())

158

viewport: Browser viewport size

159

screen: Screen size and settings

160

no_viewport: Disable default viewport

161

ignore_https_errors: Ignore HTTPS errors

162

java_script_enabled: Enable JavaScript

163

bypass_csp: Bypass Content Security Policy

164

user_agent: Custom user agent

165

locale: Locale setting

166

timezone_id: Timezone identifier

167

geolocation: Geolocation coordinates

168

permissions: Browser permissions to grant

169

extra_http_headers: Default HTTP headers

170

offline: Start in offline mode

171

http_credentials: HTTP authentication

172

device_scale_factor: Device scale factor

173

is_mobile: Mobile emulation

174

has_touch: Touch support

175

color_scheme: Color scheme preference

176

reduced_motion: Reduced motion preference

177

forced_colors: Forced colors setting

178

accept_downloads: Allow downloads

179

record_har_path: HAR file recording path

180

record_har_omit_content: Omit content from HAR

181

record_video_dir: Video recording directory

182

record_video_size: Video recording size

183

storage_state: Initial storage state

184

base_url: Base URL for relative navigation

185

strict_selectors: Enable strict selector mode

186

service_workers: Service worker handling

187

record_har_url_filter: HAR URL filter

188

record_har_mode: HAR recording mode

189

record_har_content: HAR content handling

190

191

Returns:

192

BrowserContext: Browser context with persistent state

193

"""

194

195

def connect(

196

self,

197

ws_endpoint: str,

198

timeout: Optional[float] = None,

199

slow_mo: Optional[float] = None,

200

headers: Optional[Dict[str, str]] = None

201

) -> Browser:

202

"""

203

Connect to existing browser instance via WebSocket.

204

205

Args:

206

ws_endpoint: WebSocket endpoint URL

207

timeout: Connection timeout in milliseconds

208

slow_mo: Slow down operations by milliseconds

209

headers: WebSocket headers

210

211

Returns:

212

Browser: Connected browser instance

213

"""

214

215

def connect_over_cdp(

216

self,

217

endpoint_url: str,

218

timeout: Optional[float] = None,

219

slow_mo: Optional[float] = None,

220

headers: Optional[Dict[str, str]] = None

221

) -> Browser:

222

"""

223

Connect to existing browser via Chrome DevTools Protocol.

224

225

Args:

226

endpoint_url: CDP endpoint URL

227

timeout: Connection timeout in milliseconds

228

slow_mo: Slow down operations by milliseconds

229

headers: Connection headers

230

231

Returns:

232

Browser: Connected browser instance

233

"""

234

```

235

236

### Browser Control

237

238

Manage browser instances and their lifecycle.

239

240

```python { .api }

241

class Browser:

242

"""Browser instance controlling browser process and contexts."""

243

contexts: List[BrowserContext]

244

browser_type: BrowserType

245

version: str

246

247

def new_context(

248

self,

249

viewport: Optional[ViewportSize] = None,

250

screen: Optional[Dict] = None,

251

no_viewport: Optional[bool] = None,

252

ignore_https_errors: Optional[bool] = None,

253

java_script_enabled: Optional[bool] = None,

254

bypass_csp: Optional[bool] = None,

255

user_agent: Optional[str] = None,

256

locale: Optional[str] = None,

257

timezone_id: Optional[str] = None,

258

geolocation: Optional[Geolocation] = None,

259

permissions: Optional[List[str]] = None,

260

extra_http_headers: Optional[Dict[str, str]] = None,

261

offline: Optional[bool] = None,

262

http_credentials: Optional[HttpCredentials] = None,

263

device_scale_factor: Optional[float] = None,

264

is_mobile: Optional[bool] = None,

265

has_touch: Optional[bool] = None,

266

color_scheme: Optional[str] = None,

267

reduced_motion: Optional[str] = None,

268

forced_colors: Optional[str] = None,

269

accept_downloads: Optional[bool] = None,

270

proxy: Optional[ProxySettings] = None,

271

record_har_path: Optional[str] = None,

272

record_har_omit_content: Optional[bool] = None,

273

record_video_dir: Optional[str] = None,

274

record_video_size: Optional[ViewportSize] = None,

275

storage_state: Union[str, StorageState, None] = None,

276

base_url: Optional[str] = None,

277

strict_selectors: Optional[bool] = None,

278

service_workers: Optional[str] = None,

279

record_har_url_filter: Union[str, Pattern, None] = None,

280

record_har_mode: Optional[str] = None,

281

record_har_content: Optional[str] = None

282

) -> BrowserContext:

283

"""

284

Create new browser context with independent state.

285

286

Args:

287

viewport: Browser viewport size

288

screen: Screen configuration

289

no_viewport: Disable default viewport

290

ignore_https_errors: Ignore HTTPS certificate errors

291

java_script_enabled: Enable/disable JavaScript

292

bypass_csp: Bypass Content Security Policy

293

user_agent: Custom user agent string

294

locale: Browser locale (en-US, de-DE, etc.)

295

timezone_id: Timezone identifier (America/New_York, etc.)

296

geolocation: GPS coordinates

297

permissions: Browser permissions to grant

298

extra_http_headers: Default headers for all requests

299

offline: Start in offline mode

300

http_credentials: HTTP authentication credentials

301

device_scale_factor: Device pixel ratio

302

is_mobile: Enable mobile viewport

303

has_touch: Enable touch events

304

color_scheme: 'light', 'dark', or 'no-preference'

305

reduced_motion: 'reduce', 'no-preference'

306

forced_colors: 'active', 'none'

307

accept_downloads: Allow file downloads

308

proxy: Proxy server configuration

309

record_har_path: Path to record HAR file

310

record_har_omit_content: Exclude response bodies from HAR

311

record_video_dir: Directory for video recording

312

record_video_size: Video dimensions

313

storage_state: Initial cookies and localStorage

314

base_url: Base URL for relative navigation

315

strict_selectors: Throw on ambiguous selectors

316

service_workers: 'allow', 'block'

317

record_har_url_filter: Filter URLs in HAR recording

318

record_har_mode: 'full', 'minimal'

319

record_har_content: 'omit', 'embed', 'attach'

320

321

Returns:

322

BrowserContext: New isolated browser context

323

"""

324

325

def new_page(self) -> Page:

326

"""

327

Create new page in default browser context.

328

329

Returns:

330

Page: New page instance

331

"""

332

333

def is_connected(self) -> bool:

334

"""

335

Check if browser is connected.

336

337

Returns:

338

bool: True if browser is connected

339

"""

340

341

def close(self) -> None:

342

"""Close browser instance and all contexts."""

343

344

def start_tracing(

345

self,

346

page: Optional[Page] = None,

347

path: Optional[str] = None,

348

screenshots: Optional[bool] = None,

349

categories: Optional[List[str]] = None

350

) -> None:

351

"""

352

Start tracing for performance analysis.

353

354

Args:

355

page: Page to trace (traces all if None)

356

path: Output file path

357

screenshots: Include screenshots in trace

358

categories: Trace categories to include

359

"""

360

361

def stop_tracing(self) -> bytes:

362

"""

363

Stop tracing and return trace data.

364

365

Returns:

366

bytes: Trace data

367

"""

368

```

369

370

### Context Management

371

372

Manage isolated browser sessions with independent state.

373

374

```python { .api }

375

class BrowserContext:

376

"""Isolated browser session with independent cookies, storage, and permissions."""

377

pages: List[Page]

378

browser: Optional[Browser]

379

380

def new_page(self) -> Page:

381

"""

382

Create new page in this context.

383

384

Returns:

385

Page: New page instance

386

"""

387

388

def close(self) -> None:

389

"""Close context and all associated pages."""

390

391

def cookies(self, urls: Optional[Union[str, List[str]]] = None) -> List[Cookie]:

392

"""

393

Get cookies for specified URLs.

394

395

Args:

396

urls: URL(s) to get cookies for (all if None)

397

398

Returns:

399

List[Cookie]: Current cookies

400

"""

401

402

def add_cookies(self, cookies: List[Cookie]) -> None:

403

"""

404

Add cookies to the context.

405

406

Args:

407

cookies: Cookies to add

408

"""

409

410

def clear_cookies(self) -> None:

411

"""Clear all cookies in the context."""

412

413

def grant_permissions(

414

self,

415

permissions: List[str],

416

origin: Optional[str] = None

417

) -> None:

418

"""

419

Grant specified permissions.

420

421

Args:

422

permissions: Permission names (geolocation, notifications, etc.)

423

origin: Origin to grant permissions for (all if None)

424

"""

425

426

def clear_permissions(self) -> None:

427

"""Clear all granted permissions."""

428

429

def set_geolocation(self, geolocation: Optional[Geolocation]) -> None:

430

"""

431

Set geolocation coordinates.

432

433

Args:

434

geolocation: GPS coordinates (clears if None)

435

"""

436

437

def set_extra_http_headers(self, headers: Dict[str, str]) -> None:

438

"""

439

Set default HTTP headers for all requests.

440

441

Args:

442

headers: Headers to set

443

"""

444

445

def set_offline(self, offline: bool) -> None:

446

"""

447

Toggle offline mode.

448

449

Args:

450

offline: True for offline mode

451

"""

452

453

def storage_state(self, path: Optional[str] = None) -> StorageState:

454

"""

455

Get current storage state (cookies and localStorage).

456

457

Args:

458

path: Optional file path to save state

459

460

Returns:

461

StorageState: Current storage state

462

"""

463

464

def route(

465

self,

466

url: Union[str, Pattern, Callable[[str], bool]],

467

handler: Callable[[Route], None]

468

) -> None:

469

"""

470

Intercept network requests matching URL pattern.

471

472

Args:

473

url: URL pattern to intercept

474

handler: Function to handle intercepted requests

475

"""

476

477

def unroute(

478

self,

479

url: Union[str, Pattern, Callable[[str], bool]],

480

handler: Optional[Callable[[Route], None]] = None

481

) -> None:

482

"""

483

Remove request interception.

484

485

Args:

486

url: URL pattern to stop intercepting

487

handler: Specific handler to remove (all if None)

488

"""

489

490

def expect_event(

491

self,

492

event: str,

493

predicate: Optional[Callable] = None,

494

timeout: Optional[float] = None

495

) -> EventContextManager:

496

"""

497

Wait for context event.

498

499

Args:

500

event: Event name (page, close, request, etc.)

501

predicate: Event filter function

502

timeout: Wait timeout in milliseconds

503

504

Returns:

505

EventContextManager: Context manager for event

506

"""

507

508

def wait_for_event(

509

self,

510

event: str,

511

predicate: Optional[Callable] = None,

512

timeout: Optional[float] = None

513

) -> Any:

514

"""

515

Wait for context event and return event data.

516

517

Args:

518

event: Event name

519

predicate: Event filter function

520

timeout: Wait timeout in milliseconds

521

522

Returns:

523

Any: Event data

524

"""

525

```

526

527

## Usage Examples

528

529

### Basic Browser Launch

530

531

```python

532

from playwright.sync_api import sync_playwright

533

534

# Launch different browsers

535

with sync_playwright() as p:

536

# Chromium (default)

537

browser = p.chromium.launch(headless=False)

538

539

# Firefox

540

firefox = p.firefox.launch()

541

542

# WebKit

543

webkit = p.webkit.launch()

544

545

page = browser.new_page()

546

page.goto("https://example.com")

547

548

browser.close()

549

```

550

551

### Browser with Custom Configuration

552

553

```python

554

with sync_playwright() as p:

555

browser = p.chromium.launch(

556

headless=False,

557

slow_mo=1000, # Slow down by 1 second

558

args=['--start-maximized'],

559

env={'LANG': 'en_US.UTF-8'}

560

)

561

562

context = browser.new_context(

563

viewport={'width': 1920, 'height': 1080},

564

locale='en-US',

565

timezone_id='America/New_York',

566

permissions=['geolocation'],

567

geolocation={'latitude': 40.7128, 'longitude': -74.0060}

568

)

569

570

page = context.new_page()

571

page.goto("https://example.com")

572

573

browser.close()

574

```

575

576

### Persistent Context

577

578

```python

579

with sync_playwright() as p:

580

# Browser with persistent data

581

context = p.chromium.launch_persistent_context(

582

user_data_dir="./user-data",

583

headless=False,

584

locale='en-US'

585

)

586

587

page = context.new_page()

588

page.goto("https://gmail.com") # Login will persist

589

590

context.close()

591

```

592

593

### Multiple Contexts

594

595

```python

596

with sync_playwright() as p:

597

browser = p.chromium.launch()

598

599

# Context 1: User session

600

user_context = browser.new_context(

601

storage_state={'cookies': [], 'origins': []}

602

)

603

user_page = user_context.new_page()

604

605

# Context 2: Admin session

606

admin_context = browser.new_context(

607

http_credentials={'username': 'admin', 'password': 'secret'}

608

)

609

admin_page = admin_context.new_page()

610

611

# Independent sessions

612

user_page.goto("https://app.com/user")

613

admin_page.goto("https://app.com/admin")

614

615

browser.close()

616

```

617

618

### Chrome DevTools Protocol

619

620

Direct access to Chrome DevTools Protocol for advanced browser automation and debugging capabilities.

621

622

```python { .api }

623

class CDPSession:

624

"""Chrome DevTools Protocol session for low-level browser control."""

625

626

def send(

627

self,

628

method: str,

629

params: Optional[Dict] = None

630

) -> Dict:

631

"""

632

Send CDP command to browser.

633

634

Args:

635

method: CDP method name (e.g., 'Runtime.evaluate')

636

params: Optional method parameters

637

638

Returns:

639

Dict: CDP response data

640

"""

641

642

def detach(self) -> None:

643

"""Detach from CDP session."""

644

```

645

646

Usage example:

647

648

```python

649

# Access CDP session from browser context

650

cdp = context.new_cdp_session(page)

651

652

# Execute JavaScript via CDP

653

result = cdp.send("Runtime.evaluate", {

654

"expression": "document.title",

655

"returnByValue": True

656

})

657

print(result["result"]["value"])

658

659

# Set up event listeners

660

cdp.send("Runtime.enable")

661

```