or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

api-testing.mdbrowser-management.mdelement-handling.mdindex.mdinput-simulation.mdnetwork-control.mdpage-interaction.md

browser-management.mddocs/

0

# Browser Management

1

2

Core browser lifecycle management for launching Chromium instances, creating isolated contexts, and managing browser connections.

3

4

## Capabilities

5

6

### Browser Type

7

8

Main entry point for browser operations including launching new instances and connecting to existing ones.

9

10

```typescript { .api }

11

/**

12

* Browser type interface providing methods to launch and connect to browsers

13

*/

14

interface BrowserType {

15

/** Launch a new browser instance */

16

launch(options?: LaunchOptions): Promise<Browser>;

17

/** Connect to an existing browser via WebSocket */

18

connect(wsEndpoint: string, options?: ConnectOptions): Promise<Browser>;

19

/** Connect to an existing browser via Chrome DevTools Protocol */

20

connectOverCDP(endpointURL: string, options?: ConnectOverCDPOptions): Promise<Browser>;

21

/** Get the executable path for the browser */

22

executablePath(): string;

23

/** Get the browser type name */

24

name(): string;

25

}

26

```

27

28

**Usage Examples:**

29

30

```typescript

31

import { chromium } from "playwright-chromium";

32

33

// Launch browser with custom options

34

const browser = await chromium.launch({

35

headless: false,

36

slowMo: 100,

37

args: ['--start-maximized']

38

});

39

40

// Connect to existing browser

41

const browser = await chromium.connect('ws://localhost:9222/devtools/browser');

42

43

// Connect via CDP

44

const browser = await chromium.connectOverCDP('http://localhost:9222');

45

```

46

47

### Browser Instance

48

49

Represents a browser instance with methods for creating contexts and managing the browser lifecycle.

50

51

```typescript { .api }

52

/**

53

* Browser instance providing context management and lifecycle control

54

*/

55

interface Browser {

56

/** Create a new browser context */

57

newContext(options?: BrowserContextOptions): Promise<BrowserContext>;

58

/** Get all browser contexts */

59

contexts(): BrowserContext[];

60

/** Close the browser instance */

61

close(): Promise<void>;

62

/** Check if browser is connected */

63

isConnected(): boolean;

64

/** Get browser version string */

65

version(): string;

66

/** Get the browser type */

67

browserType(): BrowserType;

68

/** Create a new CDP session */

69

newBrowserCDPSession(): Promise<CDPSession>;

70

/** Start tracing */

71

startTracing(page?: Page, options?: TracingStartOptions): Promise<void>;

72

/** Stop tracing */

73

stopTracing(): Promise<Buffer>;

74

}

75

```

76

77

**Usage Examples:**

78

79

```typescript

80

// Create multiple contexts for isolation

81

const browser = await chromium.launch();

82

const context1 = await browser.newContext({ viewport: { width: 1920, height: 1080 } });

83

const context2 = await browser.newContext({ viewport: { width: 375, height: 667 } });

84

85

// Check browser state

86

console.log(`Browser version: ${browser.version()}`);

87

console.log(`Connected: ${browser.isConnected()}`);

88

console.log(`Active contexts: ${browser.contexts().length}`);

89

90

// Cleanup

91

await browser.close();

92

```

93

94

### Browser Context

95

96

Isolated browser session providing independent cookies, storage, permissions, and page management.

97

98

```typescript { .api }

99

/**

100

* Browser context providing isolated browsing session

101

*/

102

interface BrowserContext {

103

/** Create a new page in this context */

104

newPage(): Promise<Page>;

105

/** Get all pages in this context */

106

pages(): Page[];

107

/** Close this context and all its pages */

108

close(): Promise<void>;

109

/** Get cookies from this context */

110

cookies(urls?: string | string[]): Promise<Cookie[]>;

111

/** Add cookies to this context */

112

addCookies(cookies: Cookie[]): Promise<void>;

113

/** Clear all cookies in this context */

114

clearCookies(): Promise<void>;

115

/** Grant permissions to this context */

116

grantPermissions(permissions: string[], options?: GrantPermissionsOptions): Promise<void>;

117

/** Clear all granted permissions */

118

clearPermissions(): Promise<void>;

119

/** Set geolocation for this context */

120

setGeolocation(geolocation: Geolocation | null): Promise<void>;

121

/** Set extra HTTP headers for all requests */

122

setExtraHTTPHeaders(headers: { [key: string]: string; }): Promise<void>;

123

/** Set HTTP credentials for this context */

124

setHTTPCredentials(httpCredentials: HTTPCredentials | null): Promise<void>;

125

/** Add initialization script to run on every page */

126

addInitScript(script: Function | string | { path?: string; content?: string; }, arg?: any): Promise<void>;

127

/** Expose a binding for pages to call */

128

exposeBinding(name: string, callback: BindingCallback, options?: ExposeBindingOptions): Promise<void>;

129

/** Expose a function for pages to call */

130

exposeFunction(name: string, callback: Function): Promise<void>;

131

/** Route requests matching URL pattern */

132

route(url: string | RegExp | ((url: URL) => boolean), handler: RouteHandler): Promise<void>;

133

/** Route requests using HAR file */

134

routeFromHAR(har: string, options?: RouteFromHAROptions): Promise<void>;

135

/** Remove request routing */

136

unroute(url: string | RegExp | ((url: URL) => boolean), handler?: RouteHandler): Promise<void>;

137

/** Get or save storage state */

138

storageState(options?: StorageStateOptions): Promise<StorageState>;

139

/** Wait for an event */

140

waitForEvent(event: string, optionsOrPredicate?: WaitForEventOptions | Function): Promise<any>;

141

/** Get the browser instance */

142

browser(): Browser | null;

143

/** Get background pages (Service Workers) */

144

backgroundPages(): Page[];

145

/** Get service workers */

146

serviceWorkers(): Worker[];

147

}

148

```

149

150

**Usage Examples:**

151

152

```typescript

153

// Create context with mobile device simulation

154

const context = await browser.newContext({

155

viewport: { width: 375, height: 667 },

156

userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X)',

157

isMobile: true,

158

hasTouch: true

159

});

160

161

// Set up context-wide configurations

162

await context.setGeolocation({ latitude: 37.7749, longitude: -122.4194 });

163

await context.grantPermissions(['geolocation']);

164

await context.addCookies([

165

{ name: 'session', value: 'abc123', domain: 'example.com', path: '/' }

166

]);

167

168

// Route all API calls

169

await context.route('**/api/**', route => {

170

route.fulfill({

171

status: 200,

172

body: JSON.stringify({ mocked: true })

173

});

174

});

175

176

// Multiple pages in same context share state

177

const page1 = await context.newPage();

178

const page2 = await context.newPage();

179

```

180

181

## Configuration Types

182

183

### Launch Options

184

185

```typescript { .api }

186

interface LaunchOptions {

187

/** Whether to run browser in headless mode */

188

headless?: boolean | 'new';

189

/** Slow down operations by specified milliseconds */

190

slowMo?: number;

191

/** Maximum time in milliseconds to wait for browser to start */

192

timeout?: number;

193

/** Browser distribution channel */

194

channel?: string;

195

/** Path to browser executable */

196

executablePath?: string;

197

/** Additional arguments to pass to browser */

198

args?: string[];

199

/** Network proxy settings */

200

proxy?: ProxySettings;

201

/** Path to directory for downloads */

202

downloadsPath?: string;

203

/** Enable/disable Chromium sandbox */

204

chromiumSandbox?: boolean;

205

/** Whether Playwright should handle SIGINT */

206

handleSIGINT?: boolean;

207

/** Whether Playwright should handle SIGTERM */

208

handleSIGTERM?: boolean;

209

/** Whether Playwright should handle SIGHUP */

210

handleSIGHUP?: boolean;

211

/** Logger instance for debugging */

212

logger?: Logger;

213

/** Environment variables */

214

env?: { [key: string]: string | number | boolean; };

215

}

216

```

217

218

### Connection Options

219

220

```typescript { .api }

221

interface ConnectOptions {

222

/** Maximum time to wait for connection */

223

timeout?: number;

224

/** Slow down operations by specified milliseconds */

225

slowMo?: number;

226

/** Logger instance for debugging */

227

logger?: Logger;

228

/** Additional headers for WebSocket connection */

229

headers?: { [key: string]: string; };

230

}

231

232

interface ConnectOverCDPOptions {

233

/** Maximum time to wait for connection */

234

timeout?: number;

235

/** Slow down operations by specified milliseconds */

236

slowMo?: number;

237

/** Logger instance for debugging */

238

logger?: Logger;

239

/** Endpoint URL for CDP connection */

240

endpointURL: string;

241

}

242

```

243

244

### Context Options

245

246

```typescript { .api }

247

interface BrowserContextOptions {

248

/** Viewport size, null disables default 1280x720 viewport */

249

viewport?: ViewportSize | null;

250

/** Screen size for window.screen */

251

screen?: ScreenSize;

252

/** Disable default viewport */

253

noViewport?: boolean;

254

/** Whether to ignore HTTPS errors */

255

ignoreHTTPSErrors?: boolean;

256

/** Whether JavaScript is enabled */

257

javaScriptEnabled?: boolean;

258

/** Whether to bypass CSP */

259

bypassCSP?: boolean;

260

/** User agent string */

261

userAgent?: string;

262

/** Locale identifier */

263

locale?: string;

264

/** Timezone identifier */

265

timezoneId?: string;

266

/** Geolocation settings */

267

geolocation?: Geolocation;

268

/** Permissions to grant */

269

permissions?: string[];

270

/** Extra HTTP headers for all requests */

271

extraHTTPHeaders?: { [key: string]: string; };

272

/** Whether to emulate network offline */

273

offline?: boolean;

274

/** HTTP authentication credentials */

275

httpCredentials?: HTTPCredentials;

276

/** Device scale factor */

277

deviceScaleFactor?: number;

278

/** Whether to simulate mobile device */

279

isMobile?: boolean;

280

/** Whether device has touch support */

281

hasTouch?: boolean;

282

/** Color scheme preference */

283

colorScheme?: 'light' | 'dark' | 'no-preference' | null;

284

/** Reduced motion preference */

285

reducedMotion?: 'reduce' | 'no-preference' | null;

286

/** Forced colors preference */

287

forcedColors?: 'active' | 'none' | null;

288

/** Whether to accept downloads */

289

acceptDownloads?: boolean;

290

/** HAR recording options */

291

recordHar?: RecordHarOptions;

292

/** Video recording options */

293

recordVideo?: RecordVideoOptions;

294

/** Proxy settings for this context */

295

proxy?: ProxySettings;

296

}

297

```

298

299

## Utility Types

300

301

```typescript { .api }

302

interface ViewportSize {

303

width: number;

304

height: number;

305

}

306

307

interface ScreenSize {

308

width: number;

309

height: number;

310

}

311

312

interface Geolocation {

313

latitude: number;

314

longitude: number;

315

accuracy?: number;

316

}

317

318

interface HTTPCredentials {

319

username: string;

320

password: string;

321

}

322

323

interface ProxySettings {

324

server: string;

325

bypass?: string;

326

username?: string;

327

password?: string;

328

}

329

330

interface Cookie {

331

name: string;

332

value: string;

333

domain?: string;

334

path?: string;

335

expires?: number;

336

httpOnly?: boolean;

337

secure?: boolean;

338

sameSite?: 'Strict' | 'Lax' | 'None';

339

}

340

```