0
# Browser Management
1
2
Core browser lifecycle operations including launching browsers, creating contexts, and managing browser-level settings.
3
4
## Capabilities
5
6
### Launch Browser
7
8
Launch a new browser instance with specified options.
9
10
```typescript { .api }
11
/**
12
* Launch a new browser instance
13
* @param options - Configuration options for browser launch
14
* @returns Promise resolving to Browser instance
15
*/
16
function launch(options?: LaunchOptions): Promise<Browser>;
17
18
interface LaunchOptions {
19
/** Run browser in headless mode. Can be true, false, "new" (new headless), or "shell" */
20
headless?: boolean | "new" | "shell";
21
/** Path to browser executable. If not specified, uses bundled Chromium */
22
executablePath?: string;
23
/** Additional command line arguments to pass to browser */
24
args?: string[];
25
/** Whether to ignore default arguments or specify which ones to ignore */
26
ignoreDefaultArgs?: boolean | string[];
27
/** Whether to handle SIGINT signal */
28
handleSIGINT?: boolean;
29
/** Whether to handle SIGTERM signal */
30
handleSIGTERM?: boolean;
31
/** Whether to handle SIGHUP signal */
32
handleSIGHUP?: boolean;
33
/** Maximum time to wait for browser to start (milliseconds) */
34
timeout?: number;
35
/** Whether to pipe browser stdout/stderr to process stdout/stderr */
36
dumpio?: boolean;
37
/** Environment variables to set for browser process */
38
env?: Record<string, string | undefined>;
39
/** Whether to auto-open DevTools panel for each tab */
40
devtools?: boolean;
41
/** Delay between actions in milliseconds */
42
slowMo?: number;
43
/** Default viewport for each page. Set to null to disable default viewport */
44
defaultViewport?: Viewport | null;
45
/** Whether to ignore HTTPS errors */
46
ignoreHTTPSErrors?: boolean;
47
/** Browser to launch ("chrome" or "firefox") */
48
browser?: "chrome" | "firefox";
49
/** Release channel to use (Chrome only) */
50
channel?: "chrome" | "chrome-beta" | "chrome-canary" | "chrome-dev";
51
/** Whether to wait for initial page to be created */
52
waitForInitialPage?: boolean;
53
/** Port to use for debugging. If 0, a random port is chosen */
54
debuggingPort?: number;
55
}
56
```
57
58
**Usage Examples:**
59
60
```typescript
61
import puppeteer from "puppeteer";
62
63
// Basic launch
64
const browser = await puppeteer.launch();
65
66
// Launch with options
67
const browser = await puppeteer.launch({
68
headless: false, // Run with GUI
69
slowMo: 250, // Slow down actions
70
devtools: true, // Open DevTools
71
args: ["--no-sandbox", "--disable-setuid-sandbox"]
72
});
73
74
// Launch Firefox
75
const browser = await puppeteer.launch({
76
browser: "firefox",
77
headless: true
78
});
79
```
80
81
### Connect to Browser
82
83
Connect to an existing browser instance via WebSocket.
84
85
```typescript { .api }
86
/**
87
* Connect to an existing browser instance
88
* @param options - Connection options
89
* @returns Promise resolving to Browser instance
90
*/
91
function connect(options: ConnectOptions): Promise<Browser>;
92
93
interface ConnectOptions {
94
/** WebSocket endpoint URL to connect to */
95
browserWSEndpoint?: string;
96
/** Browser HTTP endpoint URL */
97
browserURL?: string;
98
/** Whether to ignore HTTPS errors */
99
ignoreHTTPSErrors?: boolean;
100
/** Default viewport for new pages */
101
defaultViewport?: Viewport | null;
102
/** Delay between actions in milliseconds */
103
slowMo?: number;
104
/** Function to filter which targets to track */
105
targetFilter?: (target: Target) => boolean;
106
/** Transport mechanism to use */
107
transport?: ConnectionTransport;
108
/** Protocol to use for communication */
109
protocol?: "cdp" | "webDriverBiDi";
110
}
111
```
112
113
**Usage Examples:**
114
115
```typescript
116
// Connect via WebSocket endpoint
117
const browser = await puppeteer.connect({
118
browserWSEndpoint: "ws://localhost:9222/devtools/browser"
119
});
120
121
// Connect via browser URL
122
const browser = await puppeteer.connect({
123
browserURL: "http://localhost:9222"
124
});
125
```
126
127
### Browser Class
128
129
Represents a browser instance that can manage multiple contexts and pages.
130
131
```typescript { .api }
132
/**
133
* Browser instance managing contexts, pages, and targets
134
*/
135
class Browser {
136
/** Get browser version information */
137
version(): Promise<string>;
138
139
/** Get browser user agent string */
140
userAgent(): Promise<string>;
141
142
/** Get WebSocket endpoint URL */
143
wsEndpoint(): string;
144
145
/** Create new page in default browser context */
146
newPage(): Promise<Page>;
147
148
/** Get all open pages across all contexts */
149
pages(): Promise<Page[]>;
150
151
/** Get all targets (pages, workers, etc.) */
152
targets(): Target[];
153
154
/** Get browser target */
155
target(): Target;
156
157
/** Wait for target matching predicate */
158
waitForTarget(
159
predicate: (target: Target) => boolean,
160
options?: WaitForTargetOptions
161
): Promise<Target>;
162
163
/** Create new browser context (incognito-like) */
164
createBrowserContext(options?: BrowserContextOptions): Promise<BrowserContext>;
165
166
/** Get all browser contexts */
167
browserContexts(): BrowserContext[];
168
169
/** Get default browser context */
170
defaultBrowserContext(): BrowserContext;
171
172
/** Get browser child process (null if connected remotely) */
173
process(): ChildProcess | null;
174
175
/** Check if browser is connected */
176
isConnected(): boolean;
177
178
/** Close browser and all pages */
179
close(): Promise<void>;
180
181
/** Disconnect from browser (without closing) */
182
disconnect(): Promise<void>;
183
184
/** Get all cookies from all contexts */
185
cookies(): Promise<Cookie[]>;
186
187
/** Set cookies for all contexts */
188
setCookie(...cookies: CookieData[]): Promise<void>;
189
190
/** Delete cookies from all contexts */
191
deleteCookie(...cookies: Cookie[]): Promise<void>;
192
}
193
194
interface WaitForTargetOptions {
195
/** Timeout in milliseconds */
196
timeout?: number;
197
}
198
199
interface BrowserContextOptions {
200
/** Proxy server settings */
201
proxyServer?: string;
202
/** Proxy bypass list */
203
proxyBypassList?: string[];
204
/** Proxy username */
205
proxyUsername?: string;
206
/** Proxy password */
207
proxyPassword?: string;
208
}
209
210
interface CookieData {
211
/** Cookie name */
212
name: string;
213
/** Cookie value */
214
value: string;
215
/** Cookie domain */
216
domain?: string;
217
/** Cookie path */
218
path?: string;
219
/** Expiration timestamp */
220
expires?: number;
221
/** HTTP only flag */
222
httpOnly?: boolean;
223
/** Secure flag */
224
secure?: boolean;
225
/** SameSite policy */
226
sameSite?: "Strict" | "Lax" | "None";
227
}
228
```
229
230
**Usage Examples:**
231
232
```typescript
233
const browser = await puppeteer.launch();
234
235
// Get browser info
236
const version = await browser.version();
237
const userAgent = await browser.userAgent();
238
239
// Create pages
240
const page1 = await browser.newPage();
241
const page2 = await browser.newPage();
242
243
// Get all pages
244
const pages = await browser.pages();
245
console.log(`Open pages: ${pages.length}`);
246
247
// Wait for new page
248
const newPage = await browser.waitForTarget(
249
target => target.type() === "page"
250
).then(target => target.page());
251
252
// Create isolated context
253
const context = await browser.createBrowserContext();
254
const contextPage = await context.newPage();
255
256
await browser.close();
257
```
258
259
### BrowserContext Class
260
261
Isolated browser environment (incognito-like) for managing related pages with separate cookies, storage, and permissions.
262
263
```typescript { .api }
264
/**
265
* Isolated browser context with separate state
266
*/
267
class BrowserContext {
268
/** Get parent browser */
269
browser(): Browser;
270
271
/** Create new page in this context */
272
newPage(): Promise<Page>;
273
274
/** Get all pages in this context */
275
pages(): Promise<Page[]>;
276
277
/** Get all targets in this context */
278
targets(): Target[];
279
280
/** Wait for target in this context */
281
waitForTarget(
282
predicate: (target: Target) => boolean,
283
options?: WaitForTargetOptions
284
): Promise<Target>;
285
286
/** Close context and all its pages */
287
close(): Promise<void>;
288
289
/** Override permissions for origins */
290
overridePermissions(
291
origin: string,
292
permissions: Permission[]
293
): Promise<void>;
294
295
/** Clear permission overrides */
296
clearPermissionOverrides(): Promise<void>;
297
298
/** Get cookies for this context */
299
cookies(): Promise<Cookie[]>;
300
301
/** Set cookies for this context */
302
setCookie(...cookies: CookieData[]): Promise<void>;
303
304
/** Delete cookies from this context */
305
deleteCookie(...cookies: Cookie[]): Promise<void>;
306
}
307
308
type Permission =
309
| "geolocation"
310
| "midi"
311
| "notifications"
312
| "camera"
313
| "microphone"
314
| "background-sync"
315
| "ambient-light-sensor"
316
| "accelerometer"
317
| "gyroscope"
318
| "magnetometer"
319
| "accessibility-events"
320
| "clipboard-read"
321
| "clipboard-write"
322
| "payment-handler"
323
| "idle-detection"
324
| "midi-sysex";
325
```
326
327
**Usage Examples:**
328
329
```typescript
330
const browser = await puppeteer.launch();
331
332
// Create isolated context
333
const context = await browser.createBrowserContext();
334
335
// Set permissions
336
await context.overridePermissions("https://example.com", [
337
"geolocation",
338
"notifications"
339
]);
340
341
// Create page in context
342
const page = await context.newPage();
343
await page.goto("https://example.com");
344
345
// Set context-specific cookies
346
await context.setCookie({
347
name: "session",
348
value: "abc123",
349
domain: "example.com"
350
});
351
352
// Clean up
353
await context.close();
354
await browser.close();
355
```
356
357
### Utility Functions
358
359
Additional browser management utilities.
360
361
```typescript { .api }
362
/**
363
* Get default launch arguments for the browser
364
* @param options - Launch options to determine arguments for
365
* @returns Array of command line arguments
366
*/
367
function defaultArgs(options?: LaunchOptions): string[];
368
369
/**
370
* Get path to browser executable
371
* @returns Path to browser executable
372
*/
373
function executablePath(): string;
374
375
/**
376
* Remove old browser binaries from cache
377
* @returns Promise that resolves when cleanup is complete
378
*/
379
function trimCache(): Promise<void>;
380
```
381
382
**Usage Examples:**
383
384
```typescript
385
// Get default arguments
386
const args = puppeteer.defaultArgs({
387
headless: false,
388
devtools: true
389
});
390
console.log("Default args:", args);
391
392
// Get executable path
393
const execPath = puppeteer.executablePath();
394
console.log("Browser location:", execPath);
395
396
// Clean up old binaries
397
await puppeteer.trimCache();
398
```