0
# Browser Launching
1
2
Advanced browser process management with customizable launch options, signal handling, and process lifecycle control. Supports both cached and system-installed browsers with comprehensive process management capabilities.
3
4
## Capabilities
5
6
### Launch Function
7
8
Launches a browser process according to LaunchOptions, providing full control over browser startup configuration and process management.
9
10
```typescript { .api }
11
/**
12
* Launches a browser process according to LaunchOptions
13
* @param opts - Launch configuration options
14
* @returns Process instance for managing the browser process
15
*/
16
function launch(opts: LaunchOptions): Process;
17
18
interface LaunchOptions {
19
/** Absolute path to the browser's executable */
20
executablePath: string;
21
/** Enable stdio pipes for automation (default: false) */
22
pipe?: boolean;
23
/** Forward browser stdout/stderr to Node process (default: false) */
24
dumpio?: boolean;
25
/** Additional arguments to pass to browser executable */
26
args?: string[];
27
/** Environment variables for browser process */
28
env?: Record<string, string | undefined>;
29
/** Handle SIGINT signals (default: true) */
30
handleSIGINT?: boolean;
31
/** Handle SIGTERM signals (default: true) */
32
handleSIGTERM?: boolean;
33
/** Handle SIGHUP signals (default: true) */
34
handleSIGHUP?: boolean;
35
/** Spawn in detached mode (default: true except Windows) */
36
detached?: boolean;
37
/** Callback for process exit events */
38
onExit?: () => Promise<void>;
39
}
40
```
41
42
**Usage Examples:**
43
44
```typescript
45
import { launch, computeExecutablePath, Browser } from "@puppeteer/browsers";
46
47
// Basic browser launch
48
const executablePath = computeExecutablePath({
49
cacheDir: "./browsers-cache",
50
browser: Browser.CHROME,
51
buildId: "118.0.5993.70"
52
});
53
54
const browserProcess = launch({
55
executablePath,
56
args: ["--no-sandbox", "--disable-dev-shm-usage"]
57
});
58
59
console.log("Browser PID:", browserProcess.nodeProcess.pid);
60
61
// Advanced launch with custom configuration
62
const advancedProcess = launch({
63
executablePath,
64
args: ["--headless", "--disable-gpu", "--remote-debugging-port=9222"],
65
env: {
66
...process.env,
67
DISPLAY: ":99"
68
},
69
dumpio: true,
70
onExit: async () => {
71
console.log("Browser process exited");
72
}
73
});
74
75
// Wait for DevTools endpoint
76
const wsEndpoint = await advancedProcess.waitForLineOutput(
77
/DevTools listening on (ws:\/\/.*)/,
78
10000
79
);
80
console.log("DevTools endpoint:", wsEndpoint);
81
```
82
83
### Process Class
84
85
Represents a launched browser process with comprehensive lifecycle management capabilities.
86
87
```typescript { .api }
88
/**
89
* Browser process management class providing lifecycle control
90
*/
91
class Process {
92
/** Access to underlying Node.js child process */
93
get nodeProcess(): childProcess.ChildProcess;
94
95
/** Gracefully close the browser process */
96
close(): Promise<void>;
97
98
/** Returns promise that resolves when process exits */
99
hasClosed(): Promise<void>;
100
101
/** Force kill the browser process */
102
kill(): void;
103
104
/** Wait for specific output line matching regex */
105
waitForLineOutput(regex: RegExp, timeout?: number): Promise<string>;
106
}
107
```
108
109
**Usage Examples:**
110
111
```typescript
112
import { launch } from "@puppeteer/browsers";
113
114
const process = launch({ executablePath: "/path/to/browser" });
115
116
// Monitor process lifecycle
117
process.hasClosed().then(() => {
118
console.log("Browser process has exited");
119
});
120
121
// Wait for browser to start
122
try {
123
const endpoint = await process.waitForLineOutput(
124
/DevTools listening on (ws:\/\/.*)/,
125
5000
126
);
127
console.log("Browser ready:", endpoint);
128
} catch (error) {
129
console.error("Browser failed to start:", error);
130
}
131
132
// Graceful shutdown
133
await process.close();
134
```
135
136
### Compute Executable Path
137
138
Computes the executable path for a cached browser installation.
139
140
```typescript { .api }
141
/**
142
* Computes executable path for cached browser
143
* @param options - Path computation options
144
* @returns Absolute path to browser executable
145
*/
146
function computeExecutablePath(options: ComputeExecutablePathOptions): string;
147
148
interface ComputeExecutablePathOptions {
149
/** Root path to storage directory (null for relative paths) */
150
cacheDir: string | null;
151
/** Target platform (auto-detected if not provided) */
152
platform?: BrowserPlatform;
153
/** Browser type */
154
browser: Browser;
155
/** Build identifier */
156
buildId: string;
157
}
158
```
159
160
**Usage Examples:**
161
162
```typescript
163
import { computeExecutablePath, Browser, BrowserPlatform } from "@puppeteer/browsers";
164
165
// Compute path for cached browser
166
const executablePath = computeExecutablePath({
167
cacheDir: "./browsers-cache",
168
browser: Browser.CHROME,
169
buildId: "118.0.5993.70"
170
});
171
172
// Compute relative path (for portable installations)
173
const relativePath = computeExecutablePath({
174
cacheDir: null,
175
browser: Browser.CHROME,
176
buildId: "118.0.5993.70",
177
platform: BrowserPlatform.LINUX
178
});
179
180
console.log("Cached browser path:", executablePath);
181
console.log("Relative path:", relativePath);
182
```
183
184
### Compute System Executable Path
185
186
Returns path to system-wide Chrome installation by checking known installation locations.
187
188
```typescript { .api }
189
/**
190
* Returns path to system-wide Chrome installation
191
* @param options - System browser options
192
* @returns Absolute path to system browser executable
193
* @throws Error if browser not found at expected path
194
*/
195
function computeSystemExecutablePath(options: SystemOptions): string;
196
197
interface SystemOptions {
198
/** Target platform (auto-detected if not provided) */
199
platform?: BrowserPlatform;
200
/** Browser type (currently only Chrome supported) */
201
browser: Browser;
202
/** Chrome release channel to look for */
203
channel: ChromeReleaseChannel;
204
}
205
206
enum ChromeReleaseChannel {
207
STABLE = 'stable',
208
DEV = 'dev',
209
CANARY = 'canary',
210
BETA = 'beta'
211
}
212
```
213
214
**Usage Examples:**
215
216
```typescript
217
import {
218
computeSystemExecutablePath,
219
launch,
220
Browser,
221
ChromeReleaseChannel
222
} from "@puppeteer/browsers";
223
224
// Use system Chrome installation
225
try {
226
const systemChrome = computeSystemExecutablePath({
227
browser: Browser.CHROME,
228
channel: ChromeReleaseChannel.STABLE
229
});
230
231
const process = launch({
232
executablePath: systemChrome,
233
args: ["--no-first-run"]
234
});
235
236
console.log("Launched system Chrome");
237
} catch (error) {
238
console.error("System Chrome not found:", error.message);
239
}
240
241
// Try different channels
242
const channels = [
243
ChromeReleaseChannel.STABLE,
244
ChromeReleaseChannel.BETA,
245
ChromeReleaseChannel.DEV,
246
ChromeReleaseChannel.CANARY
247
];
248
249
for (const channel of channels) {
250
try {
251
const path = computeSystemExecutablePath({
252
browser: Browser.CHROME,
253
channel
254
});
255
console.log(`Found ${channel} Chrome at:`, path);
256
break;
257
} catch {
258
console.log(`${channel} Chrome not found`);
259
}
260
}
261
```
262
263
## WebSocket Endpoint Detection
264
265
Regular expressions for detecting browser WebSocket endpoints from process output.
266
267
```typescript { .api }
268
/** Regular expression for Chrome DevTools WebSocket endpoint */
269
const CDP_WEBSOCKET_ENDPOINT_REGEX: RegExp;
270
271
/** Regular expression for WebDriver BiDi WebSocket endpoint */
272
const WEBDRIVER_BIDI_WEBSOCKET_ENDPOINT_REGEX: RegExp;
273
```
274
275
**Usage Example:**
276
277
```typescript
278
import {
279
launch,
280
CDP_WEBSOCKET_ENDPOINT_REGEX,
281
WEBDRIVER_BIDI_WEBSOCKET_ENDPOINT_REGEX
282
} from "@puppeteer/browsers";
283
284
const process = launch({
285
executablePath: "/path/to/chrome",
286
args: ["--remote-debugging-port=0"]
287
});
288
289
// Wait for CDP endpoint
290
const cdpEndpoint = await process.waitForLineOutput(
291
CDP_WEBSOCKET_ENDPOINT_REGEX,
292
10000
293
);
294
295
// Wait for BiDi endpoint
296
const bidiEndpoint = await process.waitForLineOutput(
297
WEBDRIVER_BIDI_WEBSOCKET_ENDPOINT_REGEX,
298
10000
299
);
300
301
console.log("CDP:", cdpEndpoint);
302
console.log("BiDi:", bidiEndpoint);
303
```
304
305
## Error Handling
306
307
### TimeoutError
308
309
Specialized error class for timeout operations.
310
311
```typescript { .api }
312
/**
313
* Error thrown when operations timeout
314
*/
315
class TimeoutError extends Error {
316
constructor(message?: string);
317
}
318
```
319
320
**Usage Example:**
321
322
```typescript
323
import { launch, TimeoutError } from "@puppeteer/browsers";
324
325
const process = launch({ executablePath: "/path/to/browser" });
326
327
try {
328
const endpoint = await process.waitForLineOutput(
329
/DevTools listening on (ws:\/\/.*)/,
330
5000
331
);
332
console.log("Browser ready:", endpoint);
333
} catch (error) {
334
if (error instanceof TimeoutError) {
335
console.error("Browser startup timed out");
336
} else {
337
console.error("Browser launch failed:", error);
338
}
339
}
340
```
341
342
## Process Management Features
343
344
### Signal Handling
345
346
The Process class automatically handles system signals for graceful shutdown:
347
348
- **SIGINT**: Kills browser process and exits with code 130
349
- **SIGTERM/SIGHUP**: Attempts graceful browser closure
350
- **Process Exit**: Automatically cleans up browser process
351
352
### Cross-Platform Support
353
354
Process management adapts to platform differences:
355
356
- **Linux/macOS**: Uses process groups for complete process tree cleanup
357
- **Windows**: Uses `taskkill` command for reliable process termination
358
- **Detached Mode**: Automatically disabled on Windows for compatibility
359
360
### Stdio Configuration
361
362
Flexible stdio configuration for different use cases:
363
364
- **Default**: Captures stderr for endpoint detection, ignores stdout
365
- **Dumpio**: Forwards browser output to Node.js process
366
- **Pipe Mode**: Creates additional pipes for automation protocols
367
368
## Common Launch Patterns
369
370
### Headless Automation
371
372
```typescript
373
const process = launch({
374
executablePath,
375
args: [
376
"--headless",
377
"--disable-gpu",
378
"--no-sandbox",
379
"--disable-dev-shm-usage",
380
"--remote-debugging-port=9222"
381
]
382
});
383
```
384
385
### Visual Testing
386
387
```typescript
388
const process = launch({
389
executablePath,
390
args: [
391
"--disable-web-security",
392
"--allow-running-insecure-content",
393
"--window-size=1920,1080"
394
],
395
env: { DISPLAY: ":99" }
396
});
397
```
398
399
### Performance Testing
400
401
```typescript
402
const process = launch({
403
executablePath,
404
args: [
405
"--disable-extensions",
406
"--disable-plugins",
407
"--disable-images",
408
"--disable-javascript"
409
]
410
});
411
```