0
# Page Navigation & Interaction
1
2
Page-level operations for navigation, content manipulation, element interaction, and JavaScript execution within browser tabs.
3
4
## Capabilities
5
6
### Page Navigation
7
8
Navigate to URLs, manage page history, and control page lifecycle.
9
10
```typescript { .api }
11
/**
12
* Navigate to a URL
13
* @param url - URL to navigate to
14
* @param options - Navigation options
15
* @returns Promise resolving to main response or null
16
*/
17
goto(url: string, options?: GoToOptions): Promise<HTTPResponse | null>;
18
19
/**
20
* Reload the current page
21
* @param options - Reload options
22
* @returns Promise resolving to main response or null
23
*/
24
reload(options?: WaitForOptions): Promise<HTTPResponse | null>;
25
26
/**
27
* Navigate back in browser history
28
* @param options - Navigation options
29
* @returns Promise resolving to main response or null
30
*/
31
goBack(options?: WaitForOptions): Promise<HTTPResponse | null>;
32
33
/**
34
* Navigate forward in browser history
35
* @param options - Navigation options
36
* @returns Promise resolving to main response or null
37
*/
38
goForward(options?: WaitForOptions): Promise<HTTPResponse | null>;
39
40
/**
41
* Get current page URL
42
* @returns Current URL as string
43
*/
44
url(): string;
45
46
/**
47
* Get page title
48
* @returns Promise resolving to page title
49
*/
50
title(): Promise<string>;
51
52
interface GoToOptions {
53
/** Maximum navigation time in milliseconds */
54
timeout?: number;
55
/** When to consider navigation complete */
56
waitUntil?: "load" | "domcontentloaded" | "networkidle0" | "networkidle2" | Array<"load" | "domcontentloaded" | "networkidle0" | "networkidle2">;
57
/** Referer header value */
58
referer?: string;
59
}
60
61
interface WaitForOptions {
62
/** Maximum wait time in milliseconds */
63
timeout?: number;
64
/** When to consider navigation complete */
65
waitUntil?: "load" | "domcontentloaded" | "networkidle0" | "networkidle2" | Array<"load" | "domcontentloaded" | "networkidle0" | "networkidle2">;
66
}
67
```
68
69
**Usage Examples:**
70
71
```typescript
72
// Basic navigation
73
await page.goto("https://example.com");
74
75
// Navigation with options
76
await page.goto("https://example.com/login", {
77
waitUntil: "networkidle0", // Wait until no network requests for 500ms
78
timeout: 10000 // 10 second timeout
79
});
80
81
// Navigate with history
82
await page.goto("https://example.com/page1");
83
await page.goto("https://example.com/page2");
84
await page.goBack(); // Back to page1
85
await page.goForward(); // Forward to page2
86
87
// Page info
88
const url = page.url();
89
const title = await page.title();
90
```
91
92
### Content Management
93
94
Get and set page content, including HTML manipulation.
95
96
```typescript { .api }
97
/**
98
* Get full page HTML content
99
* @returns Promise resolving to HTML string
100
*/
101
content(): Promise<string>;
102
103
/**
104
* Set page HTML content
105
* @param html - HTML content to set
106
* @param options - Content setting options
107
* @returns Promise that resolves when content is set
108
*/
109
setContent(html: string, options?: WaitForOptions): Promise<void>;
110
```
111
112
**Usage Examples:**
113
114
```typescript
115
// Get page content
116
const html = await page.content();
117
console.log(html);
118
119
// Set custom content
120
await page.setContent(`
121
<html>
122
<body>
123
<h1>Custom Page</h1>
124
<p>This is custom content</p>
125
</body>
126
</html>
127
`);
128
```
129
130
### Element Selection
131
132
Find and select elements using CSS selectors or XPath.
133
134
```typescript { .api }
135
/**
136
* Find single element matching selector
137
* @param selector - CSS selector
138
* @returns Promise resolving to ElementHandle or null
139
*/
140
$(selector: string): Promise<ElementHandle | null>;
141
142
/**
143
* Find all elements matching selector
144
* @param selector - CSS selector
145
* @returns Promise resolving to array of ElementHandles
146
*/
147
$$(selector: string): Promise<ElementHandle[]>;
148
149
/**
150
* Evaluate function on single element
151
* @param selector - CSS selector
152
* @param pageFunction - Function to evaluate on element
153
* @param args - Arguments to pass to function
154
* @returns Promise resolving to function result
155
*/
156
$eval<R>(
157
selector: string,
158
pageFunction: (element: Element, ...args: any[]) => R,
159
...args: any[]
160
): Promise<R>;
161
162
/**
163
* Evaluate function on all matching elements
164
* @param selector - CSS selector
165
* @param pageFunction - Function to evaluate on elements
166
* @param args - Arguments to pass to function
167
* @returns Promise resolving to function result
168
*/
169
$$eval<R>(
170
selector: string,
171
pageFunction: (elements: Element[], ...args: any[]) => R,
172
...args: any[]
173
): Promise<R>;
174
```
175
176
**Usage Examples:**
177
178
```typescript
179
// Find single element
180
const searchBox = await page.$("#search-input");
181
if (searchBox) {
182
await searchBox.type("query");
183
}
184
185
// Find multiple elements
186
const links = await page.$$("a");
187
console.log(`Found ${links.length} links`);
188
189
// Evaluate on single element
190
const text = await page.$eval("#title", el => el.textContent);
191
192
// Evaluate on multiple elements
193
const linkData = await page.$$eval("a", anchors =>
194
anchors.map(a => ({
195
text: a.textContent?.trim(),
196
href: a.href
197
}))
198
);
199
```
200
201
### Element Interaction
202
203
Click, type, and interact with page elements using selectors.
204
205
```typescript { .api }
206
/**
207
* Click element matching selector
208
* @param selector - CSS selector
209
* @param options - Click options
210
* @returns Promise that resolves when click completes
211
*/
212
click(selector: string, options?: ClickOptions): Promise<void>;
213
214
/**
215
* Focus element matching selector
216
* @param selector - CSS selector
217
* @returns Promise that resolves when focus completes
218
*/
219
focus(selector: string): Promise<void>;
220
221
/**
222
* Hover over element matching selector
223
* @param selector - CSS selector
224
* @returns Promise that resolves when hover completes
225
*/
226
hover(selector: string): Promise<void>;
227
228
/**
229
* Select options in select element
230
* @param selector - CSS selector for select element
231
* @param values - Option values to select
232
* @returns Promise resolving to selected values
233
*/
234
select(selector: string, ...values: string[]): Promise<string[]>;
235
236
/**
237
* Tap element (touch interaction)
238
* @param selector - CSS selector
239
* @returns Promise that resolves when tap completes
240
*/
241
tap(selector: string): Promise<void>;
242
243
/**
244
* Type text into element
245
* @param selector - CSS selector
246
* @param text - Text to type
247
* @param options - Typing options
248
* @returns Promise that resolves when typing completes
249
*/
250
type(selector: string, text: string, options?: TypeOptions): Promise<void>;
251
252
interface ClickOptions {
253
/** Mouse button to click */
254
button?: "left" | "right" | "middle";
255
/** Number of clicks */
256
clickCount?: number;
257
/** Delay between mousedown and mouseup */
258
delay?: number;
259
/** Offset from element center */
260
offset?: {x: number; y: number};
261
}
262
263
interface TypeOptions {
264
/** Delay between key presses */
265
delay?: number;
266
}
267
```
268
269
**Usage Examples:**
270
271
```typescript
272
// Click elements
273
await page.click("#submit-button");
274
await page.click(".menu-item", { button: "right" }); // Right click
275
276
// Type text
277
await page.type("#username", "john_doe");
278
await page.type("#password", "secret123", { delay: 100 });
279
280
// Select options
281
await page.select("#country", "US", "CA"); // Multi-select
282
283
// Other interactions
284
await page.focus("#search-input");
285
await page.hover(".tooltip-trigger");
286
await page.tap("#mobile-button"); // Touch interaction
287
```
288
289
### Waiting Operations
290
291
Wait for various conditions before proceeding with automation.
292
293
```typescript { .api }
294
/**
295
* Wait for element to appear
296
* @param selector - CSS selector
297
* @param options - Wait options
298
* @returns Promise resolving to ElementHandle
299
*/
300
waitForSelector(
301
selector: string,
302
options?: WaitForSelectorOptions
303
): Promise<ElementHandle>;
304
305
/**
306
* Wait for function to return truthy value
307
* @param pageFunction - Function to evaluate repeatedly
308
* @param options - Wait options
309
* @param args - Arguments to pass to function
310
* @returns Promise resolving to JSHandle of result
311
*/
312
waitForFunction<R>(
313
pageFunction: (...args: any[]) => R,
314
options?: WaitForFunctionOptions,
315
...args: any[]
316
): Promise<JSHandle<R>>;
317
318
/**
319
* Wait for navigation to complete
320
* @param options - Wait options
321
* @returns Promise resolving to main response or null
322
*/
323
waitForNavigation(options?: WaitForOptions): Promise<HTTPResponse | null>;
324
325
/**
326
* Wait for network to be idle
327
* @param options - Wait options
328
* @returns Promise that resolves when network is idle
329
*/
330
waitForNetworkIdle(options?: WaitForNetworkIdleOptions): Promise<void>;
331
332
/**
333
* Wait for request matching predicate
334
* @param urlOrPredicate - URL string or predicate function
335
* @param options - Wait options
336
* @returns Promise resolving to HTTPRequest
337
*/
338
waitForRequest(
339
urlOrPredicate: string | ((request: HTTPRequest) => boolean),
340
options?: WaitTimeoutOptions
341
): Promise<HTTPRequest>;
342
343
/**
344
* Wait for response matching predicate
345
* @param urlOrPredicate - URL string or predicate function
346
* @param options - Wait options
347
* @returns Promise resolving to HTTPResponse
348
*/
349
waitForResponse(
350
urlOrPredicate: string | ((response: HTTPResponse) => boolean),
351
options?: WaitTimeoutOptions
352
): Promise<HTTPResponse>;
353
354
interface WaitForSelectorOptions {
355
/** Whether element should be visible */
356
visible?: boolean;
357
/** Whether element should be hidden */
358
hidden?: boolean;
359
/** Maximum wait time */
360
timeout?: number;
361
}
362
363
interface WaitForFunctionOptions {
364
/** Maximum wait time */
365
timeout?: number;
366
/** Polling interval */
367
polling?: "raf" | "mutation" | number;
368
}
369
370
interface WaitForNetworkIdleOptions {
371
/** Maximum wait time */
372
timeout?: number;
373
/** Idle time threshold */
374
idleTime?: number;
375
}
376
377
interface WaitTimeoutOptions {
378
/** Maximum wait time */
379
timeout?: number;
380
}
381
```
382
383
**Usage Examples:**
384
385
```typescript
386
// Wait for elements
387
await page.waitForSelector("#submit-button");
388
await page.waitForSelector(".loading", { hidden: true });
389
390
// Wait for custom conditions
391
await page.waitForFunction(() => window.dataLoaded === true);
392
await page.waitForFunction(
393
(selector) => document.querySelector(selector)?.scrollHeight > 1000,
394
{},
395
"#content"
396
);
397
398
// Wait for navigation
399
const responsePromise = page.waitForNavigation();
400
await page.click("#link");
401
const response = await responsePromise;
402
403
// Wait for network
404
await page.waitForResponse("https://api.example.com/data");
405
await page.waitForRequest(req => req.url().includes("/api/"));
406
```
407
408
### JavaScript Evaluation
409
410
Execute JavaScript code in the page context.
411
412
```typescript { .api }
413
/**
414
* Evaluate JavaScript function in page context
415
* @param pageFunction - Function to evaluate
416
* @param args - Arguments to pass to function
417
* @returns Promise resolving to function result
418
*/
419
evaluate<R>(
420
pageFunction: (...args: any[]) => R,
421
...args: any[]
422
): Promise<R>;
423
424
/**
425
* Evaluate function and get handle to result
426
* @param pageFunction - Function to evaluate
427
* @param args - Arguments to pass to function
428
* @returns Promise resolving to JSHandle of result
429
*/
430
evaluateHandle<R>(
431
pageFunction: (...args: any[]) => R,
432
...args: any[]
433
): Promise<JSHandle<R>>;
434
435
/**
436
* Add script to be evaluated on every document creation
437
* @param pageFunction - Function to evaluate
438
* @param args - Arguments to pass to function
439
* @returns Promise that resolves when script is added
440
*/
441
evaluateOnNewDocument(
442
pageFunction: (...args: any[]) => void,
443
...args: any[]
444
): Promise<void>;
445
```
446
447
**Usage Examples:**
448
449
```typescript
450
// Evaluate simple expressions
451
const title = await page.evaluate(() => document.title);
452
const windowSize = await page.evaluate(() => ({
453
width: window.innerWidth,
454
height: window.innerHeight
455
}));
456
457
// Pass arguments to evaluation
458
const result = await page.evaluate((x, y) => x + y, 2, 3); // Returns 5
459
460
// Get handle to complex objects
461
const windowHandle = await page.evaluateHandle(() => window);
462
const locationHandle = await windowHandle.getProperty("location");
463
464
// Add initialization scripts
465
await page.evaluateOnNewDocument(() => {
466
// This runs on every page load
467
window.myGlobalVar = "initialized";
468
});
469
```
470
471
### Script and Style Management
472
473
Add external scripts and stylesheets to the page.
474
475
```typescript { .api }
476
/**
477
* Add script tag to page
478
* @param options - Script tag options
479
* @returns Promise resolving to ElementHandle of script tag
480
*/
481
addScriptTag(options: AddTagOptions): Promise<ElementHandle>;
482
483
/**
484
* Add style tag to page
485
* @param options - Style tag options
486
* @returns Promise resolving to ElementHandle of style tag
487
*/
488
addStyleTag(options: AddTagOptions): Promise<ElementHandle>;
489
490
interface AddTagOptions {
491
/** URL of external resource */
492
url?: string;
493
/** Path to local file */
494
path?: string;
495
/** Inline content */
496
content?: string;
497
/** Script type (for script tags) */
498
type?: string;
499
}
500
```
501
502
**Usage Examples:**
503
504
```typescript
505
// Add external script
506
await page.addScriptTag({
507
url: "https://code.jquery.com/jquery-3.6.0.min.js"
508
});
509
510
// Add inline script
511
await page.addScriptTag({
512
content: `
513
window.utils = {
514
formatDate: (date) => date.toISOString()
515
};
516
`
517
});
518
519
// Add stylesheet
520
await page.addStyleTag({
521
url: "https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.1/normalize.min.css"
522
});
523
524
// Add inline styles
525
await page.addStyleTag({
526
content: `
527
.highlight { background-color: yellow; }
528
.hidden { display: none; }
529
`
530
});
531
```
532
533
### Page Context Information
534
535
Access page context, frames, and related browser objects.
536
537
```typescript { .api }
538
/**
539
* Get parent browser instance
540
* @returns Browser instance
541
*/
542
browser(): Browser;
543
544
/**
545
* Get browser context
546
* @returns BrowserContext instance
547
*/
548
browserContext(): BrowserContext;
549
550
/**
551
* Get page target
552
* @returns Target instance
553
*/
554
target(): Target;
555
556
/**
557
* Get main frame
558
* @returns Frame instance
559
*/
560
mainFrame(): Frame;
561
562
/**
563
* Get all frames in page
564
* @returns Array of Frame instances
565
*/
566
frames(): Frame[];
567
568
/**
569
* Get all web workers
570
* @returns Array of WebWorker instances
571
*/
572
workers(): WebWorker[];
573
574
/**
575
* Check if page is closed
576
* @returns True if page is closed
577
*/
578
isClosed(): boolean;
579
```
580
581
**Usage Examples:**
582
583
```typescript
584
// Access browser context
585
const browser = page.browser();
586
const context = page.browserContext();
587
588
// Work with frames
589
const mainFrame = page.mainFrame();
590
const allFrames = page.frames();
591
592
console.log(`Page has ${allFrames.length} frames`);
593
594
// Access workers
595
const workers = page.workers();
596
console.log(`Page has ${workers.length} web workers`);
597
598
// Check page state
599
if (!page.isClosed()) {
600
await page.evaluate(() => console.log("Page is still open"));
601
}
602
```
603
604
### Page Lifecycle
605
606
Close pages and handle page lifecycle events.
607
608
```typescript { .api }
609
/**
610
* Close the page
611
* @param options - Close options
612
* @returns Promise that resolves when page is closed
613
*/
614
close(options?: {runBeforeUnload?: boolean}): Promise<void>;
615
```
616
617
**Usage Examples:**
618
619
```typescript
620
// Close page immediately
621
await page.close();
622
623
// Close page after running beforeunload handlers
624
await page.close({ runBeforeUnload: true });
625
```
626
627
### Dialog Handling
628
629
Handle browser dialogs including alert, confirm, and prompt dialogs.
630
631
```typescript { .api }
632
/**
633
* Browser dialog (alert, confirm, prompt)
634
*/
635
class Dialog {
636
/** Get dialog type */
637
type(): DialogType;
638
639
/** Get dialog message text */
640
message(): string;
641
642
/** Get default value for prompt dialogs */
643
defaultValue(): string;
644
645
/** Accept dialog with optional text for prompts */
646
accept(promptText?: string): Promise<void>;
647
648
/** Dismiss/cancel dialog */
649
dismiss(): Promise<void>;
650
}
651
652
type DialogType = "alert" | "confirm" | "prompt" | "beforeunload";
653
```
654
655
**Usage Examples:**
656
657
```typescript
658
// Handle dialogs using event listener
659
page.on("dialog", async (dialog) => {
660
console.log(`Dialog type: ${dialog.type()}`);
661
console.log(`Dialog message: ${dialog.message()}`);
662
663
if (dialog.type() === "confirm") {
664
await dialog.accept(); // Click OK
665
} else if (dialog.type() === "prompt") {
666
await dialog.accept("My response"); // Enter text and click OK
667
} else {
668
await dialog.dismiss(); // Click Cancel or close
669
}
670
});
671
672
// Trigger dialog
673
await page.click("#show-alert");
674
675
// Or handle with waitForEvent
676
const dialogPromise = page.waitForEvent("dialog");
677
await page.click("#show-confirm");
678
const dialog = await dialogPromise;
679
await dialog.accept();
680
```