0
# Browser Automation
1
2
Complete browser automation API providing page interaction, element manipulation, and navigation across Chromium, Firefox, and WebKit browsers with automatic waiting and context isolation.
3
4
## Capabilities
5
6
### Page Navigation and Lifecycle
7
8
Functions for navigating between pages and managing page lifecycle events.
9
10
```typescript { .api }
11
/**
12
* Navigate to a URL with optional wait conditions
13
* @param url - Target URL (absolute or relative to baseURL)
14
* @param options - Navigation options
15
* @returns Promise resolving to Response object
16
*/
17
goto(url: string, options?: {
18
waitUntil?: 'load' | 'domcontentloaded' | 'networkidle';
19
timeout?: number;
20
referer?: string;
21
}): Promise<Response | null>;
22
23
/**
24
* Navigate back in browser history
25
* @param options - Navigation options
26
* @returns Promise resolving to Response object or null
27
*/
28
goBack(options?: { waitUntil?: 'load' | 'domcontentloaded' | 'networkidle'; timeout?: number }): Promise<Response | null>;
29
30
/**
31
* Navigate forward in browser history
32
* @param options - Navigation options
33
* @returns Promise resolving to Response object or null
34
*/
35
goForward(options?: { waitUntil?: 'load' | 'domcontentloaded' | 'networkidle'; timeout?: number }): Promise<Response | null>;
36
37
/**
38
* Reload the current page
39
* @param options - Reload options
40
* @returns Promise resolving to Response object or null
41
*/
42
reload(options?: { waitUntil?: 'load' | 'domcontentloaded' | 'networkidle'; timeout?: number }): Promise<Response | null>;
43
44
/**
45
* Wait for specific page load states
46
* @param state - Load state to wait for
47
* @param options - Wait options
48
*/
49
waitForLoadState(state?: 'load' | 'domcontentloaded' | 'networkidle', options?: { timeout?: number }): Promise<void>;
50
51
/**
52
* Wait for navigation to complete
53
* @param options - Navigation wait options
54
* @returns Promise resolving to Response object
55
*/
56
waitForNavigation(options?: {
57
waitUntil?: 'load' | 'domcontentloaded' | 'networkidle';
58
timeout?: number;
59
url?: string | RegExp | ((url: URL) => boolean);
60
}): Promise<Response | null>;
61
```
62
63
**Usage Examples:**
64
65
```typescript
66
// Basic navigation
67
await page.goto("https://example.com");
68
await page.goto("/dashboard"); // Relative to baseURL
69
70
// Navigation with wait conditions
71
await page.goto("/slow-page", { waitUntil: 'networkidle' });
72
73
// Browser history navigation
74
await page.goBack();
75
await page.goForward();
76
await page.reload();
77
78
// Wait for specific load states
79
await page.waitForLoadState('domcontentloaded');
80
await page.waitForNavigation({ url: /dashboard/ });
81
```
82
83
### Element Interaction
84
85
Functions for interacting with page elements including clicking, typing, and form manipulation.
86
87
```typescript { .api }
88
/**
89
* Click an element matching the selector
90
* @param selector - CSS selector or locator string
91
* @param options - Click options
92
*/
93
click(selector: string, options?: {
94
button?: 'left' | 'right' | 'middle';
95
clickCount?: number;
96
delay?: number;
97
position?: { x: number; y: number };
98
modifiers?: ('Alt' | 'Control' | 'Meta' | 'Shift')[];
99
force?: boolean;
100
noWaitAfter?: boolean;
101
timeout?: number;
102
}): Promise<void>;
103
104
/**
105
* Double-click an element
106
* @param selector - CSS selector or locator string
107
* @param options - Double-click options
108
*/
109
dblclick(selector: string, options?: {
110
delay?: number;
111
button?: 'left' | 'right' | 'middle';
112
position?: { x: number; y: number };
113
modifiers?: ('Alt' | 'Control' | 'Meta' | 'Shift')[];
114
force?: boolean;
115
noWaitAfter?: boolean;
116
timeout?: number;
117
}): Promise<void>;
118
119
/**
120
* Fill input element with text
121
* @param selector - CSS selector for input element
122
* @param value - Text to input
123
* @param options - Fill options
124
*/
125
fill(selector: string, value: string, options?: {
126
force?: boolean;
127
noWaitAfter?: boolean;
128
timeout?: number;
129
}): Promise<void>;
130
131
/**
132
* Type text with realistic timing
133
* @param selector - CSS selector for input element
134
* @param text - Text to type
135
* @param options - Type options
136
*/
137
type(selector: string, text: string, options?: {
138
delay?: number;
139
noWaitAfter?: boolean;
140
timeout?: number;
141
}): Promise<void>;
142
143
/**
144
* Press keyboard keys
145
* @param selector - CSS selector for target element
146
* @param key - Key or key combination to press
147
* @param options - Press options
148
*/
149
press(selector: string, key: string, options?: {
150
delay?: number;
151
noWaitAfter?: boolean;
152
timeout?: number;
153
}): Promise<void>;
154
155
/**
156
* Hover over an element
157
* @param selector - CSS selector for target element
158
* @param options - Hover options
159
*/
160
hover(selector: string, options?: {
161
position?: { x: number; y: number };
162
modifiers?: ('Alt' | 'Control' | 'Meta' | 'Shift')[];
163
force?: boolean;
164
timeout?: number;
165
}): Promise<void>;
166
```
167
168
**Usage Examples:**
169
170
```typescript
171
// Basic element interactions
172
await page.click("button#submit");
173
await page.fill("input[name='email']", "user@example.com");
174
await page.type("#search", "playwright testing");
175
await page.press("input", "Enter");
176
177
// Advanced click options
178
await page.click(".menu-item", {
179
button: 'right',
180
modifiers: ['Control']
181
});
182
183
// Form interactions
184
await page.fill("#username", "admin");
185
await page.fill("#password", "secret");
186
await page.click("button[type='submit']");
187
188
// Keyboard navigation
189
await page.press("body", "Tab");
190
await page.press("input", "Control+A");
191
await page.press("input", "Backspace");
192
```
193
194
### Element Selection and Waiting
195
196
Functions for selecting elements and waiting for various conditions.
197
198
```typescript { .api }
199
/**
200
* Wait for element to appear and become actionable
201
* @param selector - CSS selector for target element
202
* @param options - Wait options
203
* @returns Promise resolving to ElementHandle
204
*/
205
waitForSelector(selector: string, options?: {
206
state?: 'attached' | 'detached' | 'visible' | 'hidden';
207
timeout?: number;
208
}): Promise<ElementHandle | null>;
209
210
/**
211
* Create a locator for element(s) matching selector
212
* @param selector - CSS selector or locator string
213
* @param options - Locator options
214
* @returns Locator instance for chaining operations
215
*/
216
locator(selector: string, options?: {
217
hasText?: string | RegExp;
218
has?: Locator;
219
}): Locator;
220
221
/**
222
* Get element handle for the first matching element
223
* @param selector - CSS selector
224
* @param options - Query options
225
* @returns ElementHandle or null if not found
226
*/
227
$(selector: string, options?: { timeout?: number }): Promise<ElementHandle | null>;
228
229
/**
230
* Get element handles for all matching elements
231
* @param selector - CSS selector
232
* @returns Array of ElementHandle objects
233
*/
234
$$(selector: string): Promise<ElementHandle[]>;
235
236
/**
237
* Wait for function to return truthy value
238
* @param pageFunction - Function to evaluate repeatedly
239
* @param arg - Argument to pass to pageFunction
240
* @param options - Wait options
241
* @returns Promise resolving to function result
242
*/
243
waitForFunction<R, Arg>(
244
pageFunction: PageFunction<Arg, R>,
245
arg?: Arg,
246
options?: { timeout?: number; polling?: number | 'raf' }
247
): Promise<JSHandle<R>>;
248
```
249
250
**Usage Examples:**
251
252
```typescript
253
// Wait for elements
254
await page.waitForSelector(".loading-indicator", { state: 'detached' });
255
await page.waitForSelector("button:enabled");
256
257
// Create locators for chaining
258
const submitButton = page.locator("button[type='submit']");
259
await submitButton.click();
260
261
const todoItem = page.locator(".todo-item", { hasText: "Buy groceries" });
262
await todoItem.check();
263
264
// Element handles
265
const element = await page.$(".title");
266
const allLinks = await page.$$("a");
267
268
// Wait for custom conditions
269
await page.waitForFunction(() => document.querySelectorAll('.item').length > 5);
270
await page.waitForFunction(() => window.myApiLoaded === true);
271
```
272
273
### JavaScript Execution
274
275
Functions for executing JavaScript code within the page context.
276
277
```typescript { .api }
278
/**
279
* Execute JavaScript in page context
280
* @param pageFunction - Function to execute in page context
281
* @param arg - Argument to pass to the function
282
* @returns Promise resolving to function return value
283
*/
284
evaluate<R, Arg>(
285
pageFunction: PageFunction<Arg, R>,
286
arg?: Arg
287
): Promise<R>;
288
289
/**
290
* Execute JavaScript and return JSHandle to result
291
* @param pageFunction - Function to execute in page context
292
* @param arg - Argument to pass to the function
293
* @returns Promise resolving to JSHandle of result
294
*/
295
evaluateHandle<R, Arg>(
296
pageFunction: PageFunction<Arg, R>,
297
arg?: Arg
298
): Promise<JSHandle<R>>;
299
300
/**
301
* Add script tag to page
302
* @param options - Script tag options
303
* @returns Promise resolving to ElementHandle of script tag
304
*/
305
addScriptTag(options: {
306
url?: string;
307
path?: string;
308
content?: string;
309
type?: string;
310
}): Promise<ElementHandle>;
311
312
/**
313
* Add style tag to page
314
* @param options - Style tag options
315
* @returns Promise resolving to ElementHandle of style tag
316
*/
317
addStyleTag(options: {
318
url?: string;
319
path?: string;
320
content?: string;
321
}): Promise<ElementHandle>;
322
```
323
324
**Usage Examples:**
325
326
```typescript
327
// Execute JavaScript and get result
328
const pageTitle = await page.evaluate(() => document.title);
329
const elementCount = await page.evaluate(() => document.querySelectorAll('.item').length);
330
331
// Pass arguments to page functions
332
const result = await page.evaluate(
333
(name) => window.myApp.getUserData(name),
334
'john'
335
);
336
337
// Get handles to page objects
338
const windowHandle = await page.evaluateHandle(() => window);
339
const documentHandle = await page.evaluateHandle(() => document);
340
341
// Add external scripts and styles
342
await page.addScriptTag({ url: 'https://cdn.jsdelivr.net/npm/lodash@4/lodash.min.js' });
343
await page.addStyleTag({ content: '.highlight { background: yellow; }' });
344
```
345
346
### Screenshots and Media
347
348
Functions for capturing page screenshots, PDFs, and videos.
349
350
```typescript { .api }
351
/**
352
* Take screenshot of page or element
353
* @param options - Screenshot options
354
* @returns Promise resolving to screenshot buffer
355
*/
356
screenshot(options?: {
357
path?: string;
358
fullPage?: boolean;
359
clip?: { x: number; y: number; width: number; height: number };
360
omitBackground?: boolean;
361
type?: 'png' | 'jpeg';
362
quality?: number;
363
timeout?: number;
364
}): Promise<Buffer>;
365
366
/**
367
* Generate PDF from page (Chromium only)
368
* @param options - PDF generation options
369
* @returns Promise resolving to PDF buffer
370
*/
371
pdf(options?: {
372
path?: string;
373
scale?: number;
374
displayHeaderFooter?: boolean;
375
headerTemplate?: string;
376
footerTemplate?: string;
377
printBackground?: boolean;
378
landscape?: boolean;
379
pageRanges?: string;
380
format?: string;
381
width?: string | number;
382
height?: string | number;
383
preferCSSPageSize?: boolean;
384
margin?: {
385
top?: string | number;
386
right?: string | number;
387
bottom?: string | number;
388
left?: string | number;
389
};
390
}): Promise<Buffer>;
391
```
392
393
**Usage Examples:**
394
395
```typescript
396
// Basic screenshots
397
await page.screenshot({ path: 'homepage.png' });
398
await page.screenshot({ path: 'fullpage.png', fullPage: true });
399
400
// Element screenshots
401
const element = page.locator('.chart');
402
await element.screenshot({ path: 'chart.png' });
403
404
// Screenshot with clipping
405
await page.screenshot({
406
path: 'header.png',
407
clip: { x: 0, y: 0, width: 1200, height: 100 }
408
});
409
410
// Generate PDF
411
await page.pdf({
412
path: 'document.pdf',
413
format: 'A4',
414
printBackground: true
415
});
416
```
417
418
### Form Handling
419
420
Specialized functions for working with form elements.
421
422
```typescript { .api }
423
/**
424
* Select option(s) from select element
425
* @param selector - CSS selector for select element
426
* @param values - Option values to select
427
* @param options - Selection options
428
* @returns Array of selected option values
429
*/
430
selectOption(
431
selector: string,
432
values: string | ElementHandle | SelectOption | string[] | ElementHandle[] | SelectOption[],
433
options?: { force?: boolean; noWaitAfter?: boolean; timeout?: number }
434
): Promise<string[]>;
435
436
/**
437
* Check checkbox or radio button
438
* @param selector - CSS selector for input element
439
* @param options - Check options
440
*/
441
check(selector: string, options?: {
442
force?: boolean;
443
noWaitAfter?: boolean;
444
position?: { x: number; y: number };
445
timeout?: number;
446
}): Promise<void>;
447
448
/**
449
* Uncheck checkbox
450
* @param selector - CSS selector for checkbox element
451
* @param options - Uncheck options
452
*/
453
uncheck(selector: string, options?: {
454
force?: boolean;
455
noWaitAfter?: boolean;
456
position?: { x: number; y: number };
457
timeout?: number;
458
}): Promise<void>;
459
460
/**
461
* Set files for file input element
462
* @param selector - CSS selector for file input
463
* @param files - File paths or file objects
464
* @param options - File input options
465
*/
466
setInputFiles(
467
selector: string,
468
files: string | string[] | FilePayload | FilePayload[],
469
options?: { noWaitAfter?: boolean; timeout?: number }
470
): Promise<void>;
471
```
472
473
**Usage Examples:**
474
475
```typescript
476
// Select dropdown options
477
await page.selectOption('select#country', 'USA');
478
await page.selectOption('select#languages', ['en', 'es', 'fr']);
479
480
// Checkbox and radio interactions
481
await page.check('input#newsletter');
482
await page.uncheck('input#notifications');
483
await page.check('input[name="payment"][value="credit"]');
484
485
// File uploads
486
await page.setInputFiles('input#avatar', 'path/to/photo.jpg');
487
await page.setInputFiles('input#documents', [
488
'path/to/file1.pdf',
489
'path/to/file2.pdf'
490
]);
491
```
492
493
## Browser Context and Browser Management
494
495
### Browser Context
496
497
```typescript { .api }
498
interface BrowserContext {
499
/**
500
* Create new page in this context
501
* @returns Promise resolving to new Page instance
502
*/
503
newPage(): Promise<Page>;
504
505
/**
506
* Get all pages in this context
507
* @returns Array of Page instances
508
*/
509
pages(): Page[];
510
511
/**
512
* Close browser context and all pages
513
*/
514
close(): Promise<void>;
515
516
/**
517
* Set extra HTTP headers for all requests
518
* @param headers - Header key-value pairs
519
*/
520
setExtraHTTPHeaders(headers: Record<string, string>): Promise<void>;
521
522
/**
523
* Set geolocation for all pages
524
* @param geolocation - Latitude and longitude coordinates
525
*/
526
setGeolocation(geolocation: { latitude: number; longitude: number; accuracy?: number }): Promise<void>;
527
528
/**
529
* Get storage state (cookies and local storage)
530
* @param options - Storage state options
531
* @returns Promise resolving to storage state object
532
*/
533
storageState(options?: { path?: string }): Promise<StorageState>;
534
}
535
```
536
537
### Browser Management
538
539
```typescript { .api }
540
interface Browser {
541
/**
542
* Create new browser context
543
* @param options - Context configuration options
544
* @returns Promise resolving to new BrowserContext
545
*/
546
newContext(options?: BrowserContextOptions): Promise<BrowserContext>;
547
548
/**
549
* Get all browser contexts
550
* @returns Array of BrowserContext instances
551
*/
552
contexts(): BrowserContext[];
553
554
/**
555
* Close browser and all contexts
556
*/
557
close(): Promise<void>;
558
559
/**
560
* Get browser version string
561
* @returns Browser version
562
*/
563
version(): string;
564
565
/**
566
* Get browser type instance
567
* @returns BrowserType for this browser
568
*/
569
browserType(): BrowserType;
570
}
571
572
interface BrowserType {
573
/**
574
* Launch new browser instance
575
* @param options - Browser launch options
576
* @returns Promise resolving to Browser instance
577
*/
578
launch(options?: BrowserLaunchOptions): Promise<Browser>;
579
580
/**
581
* Connect to existing browser via WebSocket
582
* @param wsEndpoint - WebSocket endpoint URL
583
* @param options - Connection options
584
* @returns Promise resolving to Browser instance
585
*/
586
connect(wsEndpoint: string, options?: BrowserConnectOptions): Promise<Browser>;
587
588
/**
589
* Get browser type name
590
* @returns Browser name ('chromium', 'firefox', or 'webkit')
591
*/
592
name(): string;
593
}
594
```
595
596
## Core Types
597
598
### Page Interface
599
600
```typescript { .api }
601
interface Page extends EventEmitter {
602
url(): string;
603
title(): Promise<string>;
604
content(): Promise<string>;
605
setContent(html: string, options?: { waitUntil?: 'load' | 'domcontentloaded' | 'networkidle'; timeout?: number }): Promise<void>;
606
setViewportSize(viewportSize: { width: number; height: number }): Promise<void>;
607
viewportSize(): { width: number; height: number } | null;
608
isClosed(): boolean;
609
close(options?: { runBeforeUnload?: boolean }): Promise<void>;
610
}
611
```
612
613
### Locator Interface
614
615
```typescript { .api }
616
interface Locator {
617
click(options?: ClickOptions): Promise<void>;
618
fill(value: string, options?: FillOptions): Promise<void>;
619
press(key: string, options?: PressOptions): Promise<void>;
620
hover(options?: HoverOptions): Promise<void>;
621
focus(options?: { timeout?: number }): Promise<void>;
622
blur(options?: { timeout?: number }): Promise<void>;
623
624
textContent(options?: { timeout?: number }): Promise<string | null>;
625
innerText(options?: { timeout?: number }): Promise<string>;
626
innerHTML(options?: { timeout?: number }): Promise<string>;
627
getAttribute(name: string, options?: { timeout?: number }): Promise<string | null>;
628
629
isVisible(options?: { timeout?: number }): Promise<boolean>;
630
isEnabled(options?: { timeout?: number }): Promise<boolean>;
631
isEditable(options?: { timeout?: number }): Promise<boolean>;
632
isChecked(options?: { timeout?: number }): Promise<boolean>;
633
634
count(): Promise<number>;
635
first(): Locator;
636
last(): Locator;
637
nth(index: number): Locator;
638
filter(options: { hasText?: string | RegExp; has?: Locator }): Locator;
639
640
screenshot(options?: ScreenshotOptions): Promise<Buffer>;
641
waitFor(options?: { state?: 'attached' | 'detached' | 'visible' | 'hidden'; timeout?: number }): Promise<void>;
642
}
643
```
644
645
### Element Handle
646
647
```typescript { .api }
648
interface ElementHandle extends JSHandle {
649
click(options?: ClickOptions): Promise<void>;
650
fill(value: string, options?: FillOptions): Promise<void>;
651
press(key: string, options?: PressOptions): Promise<void>;
652
hover(options?: HoverOptions): Promise<void>;
653
654
boundingBox(): Promise<{ x: number; y: number; width: number; height: number } | null>;
655
screenshot(options?: ScreenshotOptions): Promise<Buffer>;
656
scrollIntoViewIfNeeded(options?: { timeout?: number }): Promise<void>;
657
658
isVisible(): Promise<boolean>;
659
isEnabled(): Promise<boolean>;
660
isEditable(): Promise<boolean>;
661
isChecked(): Promise<boolean>;
662
663
textContent(): Promise<string | null>;
664
innerText(): Promise<string>;
665
innerHTML(): Promise<string>;
666
getAttribute(name: string): Promise<string | null>;
667
668
$(selector: string): Promise<ElementHandle | null>;
669
$$(selector: string): Promise<ElementHandle[]>;
670
671
waitForElementState(state: 'visible' | 'hidden' | 'stable' | 'enabled' | 'disabled' | 'editable', options?: { timeout?: number }): Promise<void>;
672
waitForSelector(selector: string, options?: WaitForSelectorOptions): Promise<ElementHandle | null>;
673
}