UNPKG

264 kBTypeScriptView Raw
1/// <reference types="node" />
2
3import { ChildProcess } from 'child_process';
4import { Protocol } from 'devtools-protocol';
5import { ProtocolMapping } from 'devtools-protocol/types/protocol-mapping.js';
6import type { Readable } from 'stream';
7
8declare const __JSHandleSymbol: unique symbol;
9
10/**
11 * The Accessibility class provides methods for inspecting Chromium's
12 * accessibility tree. The accessibility tree is used by assistive technology
13 * such as {@link https://en.wikipedia.org/wiki/Screen_reader | screen readers} or
14 * {@link https://en.wikipedia.org/wiki/Switch_access | switches}.
15 *
16 * @remarks
17 *
18 * Accessibility is a very platform-specific thing. On different platforms,
19 * there are different screen readers that might have wildly different output.
20 *
21 * Blink - Chrome's rendering engine - has a concept of "accessibility tree",
22 * which is then translated into different platform-specific APIs. Accessibility
23 * namespace gives users access to the Blink Accessibility Tree.
24 *
25 * Most of the accessibility tree gets filtered out when converting from Blink
26 * AX Tree to Platform-specific AX-Tree or by assistive technologies themselves.
27 * By default, Puppeteer tries to approximate this filtering, exposing only
28 * the "interesting" nodes of the tree.
29 *
30 * @public
31 */
32export declare class Accessibility {
33 #private;
34 /* Excluded from this release type: __constructor */
35 /**
36 * Captures the current state of the accessibility tree.
37 * The returned object represents the root accessible node of the page.
38 *
39 * @remarks
40 *
41 * **NOTE** The Chromium accessibility tree contains nodes that go unused on
42 * most platforms and by most screen readers. Puppeteer will discard them as
43 * well for an easier to process tree, unless `interestingOnly` is set to
44 * `false`.
45 *
46 * @example
47 * An example of dumping the entire accessibility tree:
48 *
49 * ```ts
50 * const snapshot = await page.accessibility.snapshot();
51 * console.log(snapshot);
52 * ```
53 *
54 * @example
55 * An example of logging the focused node's name:
56 *
57 * ```ts
58 * const snapshot = await page.accessibility.snapshot();
59 * const node = findFocusedNode(snapshot);
60 * console.log(node && node.name);
61 *
62 * function findFocusedNode(node) {
63 * if (node.focused) return node;
64 * for (const child of node.children || []) {
65 * const foundNode = findFocusedNode(child);
66 * return foundNode;
67 * }
68 * return null;
69 * }
70 * ```
71 *
72 * @returns An AXNode object representing the snapshot.
73 */
74 snapshot(options?: SnapshotOptions): Promise<SerializedAXNode | null>;
75 private serializeTree;
76 private collectInterestingNodes;
77}
78
79/**
80 * @public
81 */
82export declare type ActionResult = 'continue' | 'abort' | 'respond';
83
84/* Excluded from this release type: addEventListener_2 */
85
86/* Excluded from this release type: ariaHandler */
87
88/* Excluded from this release type: assert */
89
90/**
91 * @public
92 */
93export declare type Awaitable<T> = T | PromiseLike<T>;
94
95declare type BeginSubclassSelectorTokens = ['.', '#', '[', ':'];
96
97/**
98 * @public
99 */
100export declare interface BoundingBox extends Point {
101 /**
102 * the width of the element in pixels.
103 */
104 width: number;
105 /**
106 * the height of the element in pixels.
107 */
108 height: number;
109}
110
111/**
112 * @public
113 */
114export declare interface BoxModel {
115 content: Point[];
116 padding: Point[];
117 border: Point[];
118 margin: Point[];
119 width: number;
120 height: number;
121}
122
123/**
124 * A Browser is created when Puppeteer connects to a Chromium instance, either through
125 * {@link PuppeteerNode.launch} or {@link Puppeteer.connect}.
126 *
127 * @remarks
128 *
129 * The Browser class extends from Puppeteer's {@link EventEmitter} class and will
130 * emit various events which are documented in the {@link BrowserEmittedEvents} enum.
131 *
132 * @example
133 * An example of using a {@link Browser} to create a {@link Page}:
134 *
135 * ```ts
136 * import puppeteer from 'puppeteer';
137 *
138 * (async () => {
139 * const browser = await puppeteer.launch();
140 * const page = await browser.newPage();
141 * await page.goto('https://example.com');
142 * await browser.close();
143 * })();
144 * ```
145 *
146 * @example
147 * An example of disconnecting from and reconnecting to a {@link Browser}:
148 *
149 * ```ts
150 * import puppeteer from 'puppeteer';
151 *
152 * (async () => {
153 * const browser = await puppeteer.launch();
154 * // Store the endpoint to be able to reconnect to Chromium
155 * const browserWSEndpoint = browser.wsEndpoint();
156 * // Disconnect puppeteer from Chromium
157 * browser.disconnect();
158 *
159 * // Use the endpoint to reestablish a connection
160 * const browser2 = await puppeteer.connect({browserWSEndpoint});
161 * // Close Chromium
162 * await browser2.close();
163 * })();
164 * ```
165 *
166 * @public
167 */
168export declare class Browser extends EventEmitter {
169 /* Excluded from this release type: __constructor */
170 /* Excluded from this release type: _attach */
171 /* Excluded from this release type: _detach */
172 /* Excluded from this release type: _targets */
173 /**
174 * The spawned browser process. Returns `null` if the browser instance was created with
175 * {@link Puppeteer.connect}.
176 */
177 process(): ChildProcess | null;
178 /* Excluded from this release type: _getIsPageTargetCallback */
179 /**
180 * Creates a new incognito browser context. This won't share cookies/cache with other
181 * browser contexts.
182 *
183 * @example
184 *
185 * ```ts
186 * (async () => {
187 * const browser = await puppeteer.launch();
188 * // Create a new incognito browser context.
189 * const context = await browser.createIncognitoBrowserContext();
190 * // Create a new page in a pristine context.
191 * const page = await context.newPage();
192 * // Do stuff
193 * await page.goto('https://example.com');
194 * })();
195 * ```
196 */
197 createIncognitoBrowserContext(options?: BrowserContextOptions): Promise<BrowserContext>;
198 /**
199 * Returns an array of all open browser contexts. In a newly created browser, this will
200 * return a single instance of {@link BrowserContext}.
201 */
202 browserContexts(): BrowserContext[];
203 /**
204 * Returns the default browser context. The default browser context cannot be closed.
205 */
206 defaultBrowserContext(): BrowserContext;
207 /* Excluded from this release type: _disposeContext */
208 /**
209 * The browser websocket endpoint which can be used as an argument to
210 * {@link Puppeteer.connect}.
211 *
212 * @returns The Browser websocket url.
213 *
214 * @remarks
215 *
216 * The format is `ws://${host}:${port}/devtools/browser/<id>`.
217 *
218 * You can find the `webSocketDebuggerUrl` from `http://${host}:${port}/json/version`.
219 * Learn more about the
220 * {@link https://chromedevtools.github.io/devtools-protocol | devtools protocol} and
221 * the {@link
222 * https://chromedevtools.github.io/devtools-protocol/#how-do-i-access-the-browser-target
223 * | browser endpoint}.
224 */
225 wsEndpoint(): string;
226 /**
227 * Promise which resolves to a new {@link Page} object. The Page is created in
228 * a default browser context.
229 */
230 newPage(): Promise<Page>;
231 /* Excluded from this release type: _createPageInContext */
232 /**
233 * All active targets inside the Browser. In case of multiple browser contexts, returns
234 * an array with all the targets in all browser contexts.
235 */
236 targets(): Target[];
237 /**
238 * The target associated with the browser.
239 */
240 target(): Target;
241 /**
242 * Searches for a target in all browser contexts.
243 *
244 * @param predicate - A function to be run for every target.
245 * @returns The first target found that matches the `predicate` function.
246 *
247 * @example
248 *
249 * An example of finding a target for a page opened via `window.open`:
250 *
251 * ```ts
252 * await page.evaluate(() => window.open('https://www.example.com/'));
253 * const newWindowTarget = await browser.waitForTarget(
254 * target => target.url() === 'https://www.example.com/'
255 * );
256 * ```
257 */
258 waitForTarget(predicate: (x: Target) => boolean | Promise<boolean>, options?: WaitForTargetOptions): Promise<Target>;
259 /**
260 * An array of all open pages inside the Browser.
261 *
262 * @remarks
263 *
264 * In case of multiple browser contexts, returns an array with all the pages in all
265 * browser contexts. Non-visible pages, such as `"background_page"`, will not be listed
266 * here. You can find them using {@link Target.page}.
267 */
268 pages(): Promise<Page[]>;
269 /**
270 * A string representing the browser name and version.
271 *
272 * @remarks
273 *
274 * For headless Chromium, this is similar to `HeadlessChrome/61.0.3153.0`. For
275 * non-headless, this is similar to `Chrome/61.0.3153.0`.
276 *
277 * The format of browser.version() might change with future releases of Chromium.
278 */
279 version(): Promise<string>;
280 /**
281 * The browser's original user agent. Pages can override the browser user agent with
282 * {@link Page.setUserAgent}.
283 */
284 userAgent(): Promise<string>;
285 /**
286 * Closes Chromium and all of its pages (if any were opened). The {@link Browser} object
287 * itself is considered to be disposed and cannot be used anymore.
288 */
289 close(): Promise<void>;
290 /**
291 * Disconnects Puppeteer from the browser, but leaves the Chromium process running.
292 * After calling `disconnect`, the {@link Browser} object is considered disposed and
293 * cannot be used anymore.
294 */
295 disconnect(): void;
296 /**
297 * Indicates that the browser is connected.
298 */
299 isConnected(): boolean;
300}
301
302/* Excluded from this release type: BrowserCloseCallback */
303
304/**
305 * Generic browser options that can be passed when launching any browser or when
306 * connecting to an existing browser instance.
307 * @public
308 */
309export declare interface BrowserConnectOptions {
310 /**
311 * Whether to ignore HTTPS errors during navigation.
312 * @defaultValue false
313 */
314 ignoreHTTPSErrors?: boolean;
315 /**
316 * Sets the viewport for each page.
317 */
318 defaultViewport?: Viewport | null;
319 /**
320 * Slows down Puppeteer operations by the specified amount of milliseconds to
321 * aid debugging.
322 */
323 slowMo?: number;
324 /**
325 * Callback to decide if Puppeteer should connect to a given target or not.
326 */
327 targetFilter?: TargetFilterCallback;
328 /* Excluded from this release type: _isPageTarget */
329 /* Excluded from this release type: protocol */
330}
331
332/**
333 * BrowserContexts provide a way to operate multiple independent browser
334 * sessions. When a browser is launched, it has a single BrowserContext used by
335 * default. The method {@link Browser.newPage | Browser.newPage} creates a page
336 * in the default browser context.
337 *
338 * @remarks
339 *
340 * The Browser class extends from Puppeteer's {@link EventEmitter} class and
341 * will emit various events which are documented in the
342 * {@link BrowserContextEmittedEvents} enum.
343 *
344 * If a page opens another page, e.g. with a `window.open` call, the popup will
345 * belong to the parent page's browser context.
346 *
347 * Puppeteer allows creation of "incognito" browser contexts with
348 * {@link Browser.createIncognitoBrowserContext | Browser.createIncognitoBrowserContext}
349 * method. "Incognito" browser contexts don't write any browsing data to disk.
350 *
351 * @example
352 *
353 * ```ts
354 * // Create a new incognito browser context
355 * const context = await browser.createIncognitoBrowserContext();
356 * // Create a new page inside context.
357 * const page = await context.newPage();
358 * // ... do stuff with page ...
359 * await page.goto('https://example.com');
360 * // Dispose context once it's no longer needed.
361 * await context.close();
362 * ```
363 *
364 * @public
365 */
366export declare class BrowserContext extends EventEmitter {
367 /* Excluded from this release type: __constructor */
368 /**
369 * An array of all active targets inside the browser context.
370 */
371 targets(): Target[];
372 /**
373 * This searches for a target in this specific browser context.
374 *
375 * @example
376 * An example of finding a target for a page opened via `window.open`:
377 *
378 * ```ts
379 * await page.evaluate(() => window.open('https://www.example.com/'));
380 * const newWindowTarget = await browserContext.waitForTarget(
381 * target => target.url() === 'https://www.example.com/'
382 * );
383 * ```
384 *
385 * @param predicate - A function to be run for every target
386 * @param options - An object of options. Accepts a timeout,
387 * which is the maximum wait time in milliseconds.
388 * Pass `0` to disable the timeout. Defaults to 30 seconds.
389 * @returns Promise which resolves to the first target found
390 * that matches the `predicate` function.
391 */
392 waitForTarget(predicate: (x: Target) => boolean | Promise<boolean>, options?: {
393 timeout?: number;
394 }): Promise<Target>;
395 /**
396 * An array of all pages inside the browser context.
397 *
398 * @returns Promise which resolves to an array of all open pages.
399 * Non visible pages, such as `"background_page"`, will not be listed here.
400 * You can find them using {@link Target.page | the target page}.
401 */
402 pages(): Promise<Page[]>;
403 /**
404 * Returns whether BrowserContext is incognito.
405 * The default browser context is the only non-incognito browser context.
406 *
407 * @remarks
408 * The default browser context cannot be closed.
409 */
410 isIncognito(): boolean;
411 /**
412 * @example
413 *
414 * ```ts
415 * const context = browser.defaultBrowserContext();
416 * await context.overridePermissions('https://html5demos.com', [
417 * 'geolocation',
418 * ]);
419 * ```
420 *
421 * @param origin - The origin to grant permissions to, e.g. "https://example.com".
422 * @param permissions - An array of permissions to grant.
423 * All permissions that are not listed here will be automatically denied.
424 */
425 overridePermissions(origin: string, permissions: Permission[]): Promise<void>;
426 /**
427 * Clears all permission overrides for the browser context.
428 *
429 * @example
430 *
431 * ```ts
432 * const context = browser.defaultBrowserContext();
433 * context.overridePermissions('https://example.com', ['clipboard-read']);
434 * // do stuff ..
435 * context.clearPermissionOverrides();
436 * ```
437 */
438 clearPermissionOverrides(): Promise<void>;
439 /**
440 * Creates a new page in the browser context.
441 */
442 newPage(): Promise<Page>;
443 /**
444 * The browser this browser context belongs to.
445 */
446 browser(): Browser;
447 /**
448 * Closes the browser context. All the targets that belong to the browser context
449 * will be closed.
450 *
451 * @remarks
452 * Only incognito browser contexts can be closed.
453 */
454 close(): Promise<void>;
455 get id(): string | undefined;
456}
457
458/**
459 * @public
460 */
461export declare const enum BrowserContextEmittedEvents {
462 /**
463 * Emitted when the url of a target inside the browser context changes.
464 * Contains a {@link Target} instance.
465 */
466 TargetChanged = "targetchanged",
467 /**
468 * Emitted when a target is created within the browser context, for example
469 * when a new page is opened by
470 * {@link https://developer.mozilla.org/en-US/docs/Web/API/Window/open | window.open}
471 * or by {@link BrowserContext.newPage | browserContext.newPage}
472 *
473 * Contains a {@link Target} instance.
474 */
475 TargetCreated = "targetcreated",
476 /**
477 * Emitted when a target is destroyed within the browser context, for example
478 * when a page is closed. Contains a {@link Target} instance.
479 */
480 TargetDestroyed = "targetdestroyed"
481}
482
483/**
484 * BrowserContext options.
485 *
486 * @public
487 */
488export declare interface BrowserContextOptions {
489 /**
490 * Proxy server with optional port to use for all requests.
491 * Username and password can be set in `Page.authenticate`.
492 */
493 proxyServer?: string;
494 /**
495 * Bypass the proxy for the given list of hosts.
496 */
497 proxyBypassList?: string[];
498}
499
500/**
501 * All the events a {@link Browser | browser instance} may emit.
502 *
503 * @public
504 */
505export declare const enum BrowserEmittedEvents {
506 /**
507 * Emitted when Puppeteer gets disconnected from the Chromium instance. This
508 * might happen because of one of the following:
509 *
510 * - Chromium is closed or crashed
511 *
512 * - The {@link Browser.disconnect | browser.disconnect } method was called.
513 */
514 Disconnected = "disconnected",
515 /**
516 * Emitted when the url of a target changes. Contains a {@link Target} instance.
517 *
518 * @remarks
519 *
520 * Note that this includes target changes in incognito browser contexts.
521 */
522 TargetChanged = "targetchanged",
523 /**
524 * Emitted when a target is created, for example when a new page is opened by
525 * {@link https://developer.mozilla.org/en-US/docs/Web/API/Window/open | window.open}
526 * or by {@link Browser.newPage | browser.newPage}
527 *
528 * Contains a {@link Target} instance.
529 *
530 * @remarks
531 *
532 * Note that this includes target creations in incognito browser contexts.
533 */
534 TargetCreated = "targetcreated",
535 /**
536 * Emitted when a target is destroyed, for example when a page is closed.
537 * Contains a {@link Target} instance.
538 *
539 * @remarks
540 *
541 * Note that this includes target destructions in incognito browser contexts.
542 */
543 TargetDestroyed = "targetdestroyed"
544}
545
546/**
547 * BrowserFetcher can download and manage different versions of Chromium and
548 * Firefox.
549 *
550 * @remarks
551 * BrowserFetcher operates on revision strings that specify a precise version of
552 * Chromium, e.g. `"533271"`. Revision strings can be obtained from
553 * {@link http://omahaproxy.appspot.com/ | omahaproxy.appspot.com}. For Firefox,
554 * BrowserFetcher downloads Firefox Nightly and operates on version numbers such
555 * as `"75"`.
556 *
557 * @remarks
558 * The default constructed fetcher will always be for Chromium unless otherwise
559 * specified.
560 *
561 * @remarks
562 * BrowserFetcher is not designed to work concurrently with other instances of
563 * BrowserFetcher that share the same downloads directory.
564 *
565 * @example
566 * An example of using BrowserFetcher to download a specific version of Chromium
567 * and running Puppeteer against it:
568 *
569 * ```ts
570 * const browserFetcher = new BrowserFetcher({path: 'path/to/download/folder'});
571 * const revisionInfo = await browserFetcher.download('533271');
572 * const browser = await puppeteer.launch({
573 * executablePath: revisionInfo.executablePath,
574 * });
575 * ```
576 *
577 * @public
578 */
579export declare class BrowserFetcher {
580 #private;
581 /**
582 * Constructs a browser fetcher for the given options.
583 */
584 constructor(options: BrowserFetcherOptions);
585 /**
586 * @returns Returns the current `Platform`, which is one of `mac`, `linux`,
587 * `win32` or `win64`.
588 */
589 platform(): Platform;
590 /**
591 * @returns Returns the current `Product`, which is one of `chrome` or
592 * `firefox`.
593 */
594 product(): Product;
595 /**
596 * @returns The download host being used.
597 */
598 host(): string;
599 /**
600 * Initiates a HEAD request to check if the revision is available.
601 * @remarks
602 * This method is affected by the current `product`.
603 * @param revision - The revision to check availability for.
604 * @returns A promise that resolves to `true` if the revision could be downloaded
605 * from the host.
606 */
607 canDownload(revision: string): Promise<boolean>;
608 /**
609 * Initiates a GET request to download the revision from the host.
610 * @remarks
611 * This method is affected by the current `product`.
612 * @param revision - The revision to download.
613 * @param progressCallback - A function that will be called with two arguments:
614 * How many bytes have been downloaded and the total number of bytes of the download.
615 * @returns A promise with revision information when the revision is downloaded
616 * and extracted.
617 */
618 download(revision: string, progressCallback?: (x: number, y: number) => void): Promise<BrowserFetcherRevisionInfo | undefined>;
619 /**
620 * @remarks
621 * This method is affected by the current `product`.
622 * @returns A list of all revision strings (for the current `product`)
623 * available locally on disk.
624 */
625 localRevisions(): string[];
626 /**
627 * @remarks
628 * This method is affected by the current `product`.
629 * @param revision - A revision to remove for the current `product`.
630 * @returns A promise that resolves when the revision has been removes or
631 * throws if the revision has not been downloaded.
632 */
633 remove(revision: string): Promise<void>;
634 /**
635 * @param revision - The revision to get info for.
636 * @returns The revision info for the given revision.
637 */
638 revisionInfo(revision: string): BrowserFetcherRevisionInfo;
639}
640
641/**
642 * @public
643 */
644export declare interface BrowserFetcherOptions {
645 /**
646 * Determines the path to download browsers to.
647 */
648 path: string;
649 /**
650 * Determines which platform the browser will be suited for.
651 *
652 * @defaultValue Auto-detected.
653 */
654 platform?: Platform;
655 /**
656 * Determines which product the {@link BrowserFetcher} is for.
657 *
658 * @defaultValue `"chrome"`.
659 */
660 product?: 'chrome' | 'firefox';
661 /**
662 * Determines the host that will be used for downloading.
663 *
664 * @defaultValue Either
665 *
666 * - https://storage.googleapis.com or
667 * - https://archive.mozilla.org/pub/firefox/nightly/latest-mozilla-central
668 *
669 */
670 host?: string;
671 /**
672 * Enables the use of the Chromium binary for macOS ARM.
673 *
674 * @experimental
675 */
676 useMacOSARMBinary?: boolean;
677}
678
679/**
680 * @public
681 */
682export declare interface BrowserFetcherRevisionInfo {
683 folderPath: string;
684 executablePath: string;
685 url: string;
686 local: boolean;
687 revision: string;
688 product: string;
689}
690
691/**
692 * Launcher options that only apply to Chrome.
693 *
694 * @public
695 */
696export declare interface BrowserLaunchArgumentOptions {
697 /**
698 * Whether to run the browser in headless mode.
699 * @defaultValue true
700 */
701 headless?: boolean | 'new';
702 /**
703 * Path to a user data directory.
704 * {@link https://chromium.googlesource.com/chromium/src/+/refs/heads/main/docs/user_data_dir.md | see the Chromium docs}
705 * for more info.
706 */
707 userDataDir?: string;
708 /**
709 * Whether to auto-open a DevTools panel for each tab. If this is set to
710 * `true`, then `headless` will be forced to `false`.
711 * @defaultValue `false`
712 */
713 devtools?: boolean;
714 /**
715 *
716 */
717 debuggingPort?: number;
718 /**
719 * Additional command line arguments to pass to the browser instance.
720 */
721 args?: string[];
722}
723
724/* Excluded from this release type: BrowserRunner */
725
726/* Excluded from this release type: BrowserWebSocketTransport */
727
728/* Excluded from this release type: CDPBrowser */
729
730/* Excluded from this release type: CDPBrowserContext */
731
732/* Excluded from this release type: CDPPage */
733
734/**
735 * The `CDPSession` instances are used to talk raw Chrome Devtools Protocol.
736 *
737 * @remarks
738 *
739 * Protocol methods can be called with {@link CDPSession.send} method and protocol
740 * events can be subscribed to with `CDPSession.on` method.
741 *
742 * Useful links: {@link https://chromedevtools.github.io/devtools-protocol/ | DevTools Protocol Viewer}
743 * and {@link https://github.com/aslushnikov/getting-started-with-cdp/blob/HEAD/README.md | Getting Started with DevTools Protocol}.
744 *
745 * @example
746 *
747 * ```ts
748 * const client = await page.target().createCDPSession();
749 * await client.send('Animation.enable');
750 * client.on('Animation.animationCreated', () =>
751 * console.log('Animation created!')
752 * );
753 * const response = await client.send('Animation.getPlaybackRate');
754 * console.log('playback rate is ' + response.playbackRate);
755 * await client.send('Animation.setPlaybackRate', {
756 * playbackRate: response.playbackRate / 2,
757 * });
758 * ```
759 *
760 * @public
761 */
762export declare class CDPSession extends EventEmitter {
763 /* Excluded from this release type: __constructor */
764 connection(): Connection | undefined;
765 send<T extends keyof ProtocolMapping.Commands>(method: T, ...paramArgs: ProtocolMapping.Commands[T]['paramsType']): Promise<ProtocolMapping.Commands[T]['returnType']>;
766 /**
767 * Detaches the cdpSession from the target. Once detached, the cdpSession object
768 * won't emit any events and can't be used to send messages.
769 */
770 detach(): Promise<void>;
771 /**
772 * Returns the session's id.
773 */
774 id(): string;
775}
776
777declare interface CDPSession_2 extends EventEmitter {
778 send<T extends keyof ProtocolMapping.Commands>(method: T, ...paramArgs: ProtocolMapping.Commands[T]['paramsType']): Promise<ProtocolMapping.Commands[T]['returnType']>;
779}
780
781declare interface CDPSession_3 extends EventEmitter {
782 send<T extends keyof ProtocolMapping.Commands>(method: T, ...paramArgs: ProtocolMapping.Commands[T]['paramsType']): Promise<ProtocolMapping.Commands[T]['returnType']>;
783}
784
785/* Excluded from this release type: CDPSessionEmittedEvents */
786
787/* Excluded from this release type: CDPSessionImpl */
788
789/**
790 * @public
791 */
792export declare interface CDPSessionOnMessageObject {
793 id?: number;
794 method: string;
795 params: Record<string, unknown>;
796 error: {
797 message: string;
798 data: any;
799 code: number;
800 };
801 result?: any;
802}
803
804/* Excluded from this release type: ChromeLauncher */
805
806/**
807 * @public
808 */
809export declare type ChromeReleaseChannel = 'chrome' | 'chrome-beta' | 'chrome-canary' | 'chrome-dev';
810
811/* Excluded from this release type: ChromeTargetManager */
812
813/**
814 * @deprecated Import {@link Puppeteer} and use the static method
815 * {@link Puppeteer.clearCustomQueryHandlers}
816 *
817 * @public
818 */
819export declare function clearCustomQueryHandlers(): void;
820
821/**
822 * @public
823 */
824export declare interface ClickOptions {
825 /**
826 * Time to wait between `mousedown` and `mouseup` in milliseconds.
827 *
828 * @defaultValue 0
829 */
830 delay?: number;
831 /**
832 * @defaultValue 'left'
833 */
834 button?: MouseButton;
835 /**
836 * @defaultValue 1
837 */
838 clickCount?: number;
839 /**
840 * Offset for the clickable point relative to the top-left corner of the border box.
841 */
842 offset?: Offset;
843}
844
845declare type CombinatorTokens = [' ', '>', '+', '~', '|', '|'];
846
847declare interface CommandResponse {
848 id: number;
849 result: object;
850}
851
852/**
853 * @public
854 */
855export declare interface CommonEventEmitter {
856 on(event: EventType, handler: Handler): CommonEventEmitter;
857 off(event: EventType, handler: Handler): CommonEventEmitter;
858 addListener(event: EventType, handler: Handler): CommonEventEmitter;
859 removeListener(event: EventType, handler: Handler): CommonEventEmitter;
860 emit(event: EventType, eventData?: unknown): boolean;
861 once(event: EventType, handler: Handler): CommonEventEmitter;
862 listenerCount(event: string): number;
863 removeAllListeners(event?: EventType): CommonEventEmitter;
864}
865
866/* Excluded from this release type: CommonPuppeteerSettings */
867
868declare type CompoundSelectorsOfComplexSelector<ComplexSelector extends string> = SplitWithDelemiters<ComplexSelector, CombinatorTokens> extends infer IntermediateTokens ? IntermediateTokens extends readonly string[] ? Drop<IntermediateTokens, ''> : never : never;
869
870/**
871 * Defines options to configure Puppeteer's behavior during installation and
872 * runtime.
873 *
874 * See individual properties for more information.
875 *
876 * @public
877 */
878export declare interface Configuration {
879 /**
880 * Specifies a certain version of the browser you'd like Puppeteer to use.
881 *
882 * Can be overridden by `PUPPETEER_BROWSER_REVISION`.
883 *
884 * See {@link PuppeteerNode.launch | puppeteer.launch} on how executable path
885 * is inferred.
886 *
887 * @defaultValue A compatible-revision of the browser.
888 */
889 browserRevision?: string;
890 /**
891 * Defines the directory to be used by Puppeteer for caching.
892 *
893 * Can be overridden by `PUPPETEER_CACHE_DIR`.
894 *
895 * @defaultValue `path.join(os.homedir(), '.cache', 'puppeteer')`
896 */
897 cacheDirectory?: string;
898 /**
899 * Specifies the URL prefix that is used to download Chromium.
900 *
901 * Can be overridden by `PUPPETEER_DOWNLOAD_HOST`.
902 *
903 * @remarks
904 * This must include the protocol and may even need a path prefix.
905 *
906 * @defaultValue Either https://storage.googleapis.com or
907 * https://archive.mozilla.org/pub/firefox/nightly/latest-mozilla-central,
908 * depending on the product.
909 */
910 downloadHost?: string;
911 /**
912 * Specifies the path for the downloads folder.
913 *
914 * Can be overridden by `PUPPETEER_DOWNLOAD_PATH`.
915 *
916 * @defaultValue `<cache>/<product>` where `<cache>` is Puppeteer's cache
917 * directory and `<product>` is the name of the browser.
918 */
919 downloadPath?: string;
920 /**
921 * Specifies an executable path to be used in
922 * {@link PuppeteerNode.launch | puppeteer.launch}.
923 *
924 * Can be overridden by `PUPPETEER_EXECUTABLE_PATH`.
925 *
926 * @defaultValue Auto-computed.
927 */
928 executablePath?: string;
929 /**
930 * Specifies which browser you'd like Puppeteer to use.
931 *
932 * Can be overridden by `PUPPETEER_PRODUCT`.
933 *
934 * @defaultValue `'chrome'`
935 */
936 defaultProduct?: Product;
937 /**
938 * Defines the directory to be used by Puppeteer for creating temporary files.
939 *
940 * Can be overridden by `PUPPETEER_TMP_DIR`.
941 *
942 * @defaultValue `os.tmpdir()`
943 */
944 temporaryDirectory?: string;
945 /**
946 * Tells Puppeteer to not download during installation.
947 *
948 * Can be overridden by `PUPPETEER_SKIP_DOWNLOAD`.
949 */
950 skipDownload?: boolean;
951 /**
952 * Tells Puppeteer to log at the given level.
953 *
954 * At the moment, any option silences logging.
955 *
956 * @defaultValue `undefined`
957 */
958 logLevel?: 'silent' | 'error' | 'warn';
959 /**
960 * Defines experimental options for Puppeteer.
961 */
962 experiments?: ExperimentsConfiguration;
963}
964
965export declare const connect: (options: ConnectOptions) => Promise<Browser>;
966
967/**
968 * @public
969 */
970export declare class Connection extends EventEmitter {
971 #private;
972 constructor(url: string, transport: ConnectionTransport, delay?: number);
973 static fromSession(session: CDPSession): Connection | undefined;
974 /* Excluded from this release type: _closed */
975 /* Excluded from this release type: _sessions */
976 /**
977 * @param sessionId - The session id
978 * @returns The current CDP session if it exists
979 */
980 session(sessionId: string): CDPSession | null;
981 url(): string;
982 send<T extends keyof ProtocolMapping.Commands>(method: T, ...paramArgs: ProtocolMapping.Commands[T]['paramsType']): Promise<ProtocolMapping.Commands[T]['returnType']>;
983 /* Excluded from this release type: _rawSend */
984 /* Excluded from this release type: onMessage */
985 dispose(): void;
986 /* Excluded from this release type: isAutoAttached */
987 /* Excluded from this release type: _createSession */
988 /**
989 * @param targetInfo - The target info
990 * @returns The CDP session that is created
991 */
992 createSession(targetInfo: Protocol.Target.TargetInfo): Promise<CDPSession>;
993}
994
995/* Excluded from this release type: Connection_2 */
996
997/**
998 * @public
999 */
1000export declare interface ConnectionCallback {
1001 resolve(args: unknown): void;
1002 reject(args: unknown): void;
1003 error: ProtocolError;
1004 method: string;
1005}
1006
1007/* Excluded from this release type: ConnectionEmittedEvents */
1008
1009/**
1010 * Copyright 2020 Google Inc. All rights reserved.
1011 *
1012 * Licensed under the Apache License, Version 2.0 (the "License");
1013 * you may not use this file except in compliance with the License.
1014 * You may obtain a copy of the License at
1015 *
1016 * http://www.apache.org/licenses/LICENSE-2.0
1017 *
1018 * Unless required by applicable law or agreed to in writing, software
1019 * distributed under the License is distributed on an "AS IS" BASIS,
1020 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1021 * See the License for the specific language governing permissions and
1022 * limitations under the License.
1023 */
1024/**
1025 * @public
1026 */
1027export declare interface ConnectionTransport {
1028 send(message: string): void;
1029 close(): void;
1030 onmessage?: (message: string) => void;
1031 onclose?: () => void;
1032}
1033
1034/**
1035 * @public
1036 */
1037export declare interface ConnectOptions extends BrowserConnectOptions {
1038 browserWSEndpoint?: string;
1039 browserURL?: string;
1040 transport?: ConnectionTransport;
1041 /**
1042 * Headers to use for the web socket connection.
1043 * @remarks
1044 * Only works in the Node.js environment.
1045 */
1046 headers?: Record<string, string>;
1047}
1048
1049/* Excluded from this release type: _connectToCDPBrowser */
1050
1051/* Excluded from this release type: ConsoleAPICalledCallback */
1052
1053/**
1054 * ConsoleMessage objects are dispatched by page via the 'console' event.
1055 * @public
1056 */
1057export declare class ConsoleMessage {
1058 #private;
1059 /**
1060 * @public
1061 */
1062 constructor(type: ConsoleMessageType, text: string, args: JSHandle[], stackTraceLocations: ConsoleMessageLocation[]);
1063 /**
1064 * @returns The type of the console message.
1065 */
1066 type(): ConsoleMessageType;
1067 /**
1068 * @returns The text of the console message.
1069 */
1070 text(): string;
1071 /**
1072 * @returns An array of arguments passed to the console.
1073 */
1074 args(): JSHandle[];
1075 /**
1076 * @returns The location of the console message.
1077 */
1078 location(): ConsoleMessageLocation;
1079 /**
1080 * @returns The array of locations on the stack of the console message.
1081 */
1082 stackTrace(): ConsoleMessageLocation[];
1083}
1084
1085/**
1086 * @public
1087 */
1088export declare interface ConsoleMessageLocation {
1089 /**
1090 * URL of the resource if known or `undefined` otherwise.
1091 */
1092 url?: string;
1093 /**
1094 * 0-based line number in the resource if known or `undefined` otherwise.
1095 */
1096 lineNumber?: number;
1097 /**
1098 * 0-based column number in the resource if known or `undefined` otherwise.
1099 */
1100 columnNumber?: number;
1101}
1102
1103/**
1104 * The supported types for console messages.
1105 * @public
1106 */
1107export declare type ConsoleMessageType = 'log' | 'debug' | 'info' | 'error' | 'warning' | 'dir' | 'dirxml' | 'table' | 'trace' | 'clear' | 'startGroup' | 'startGroupCollapsed' | 'endGroup' | 'assert' | 'profile' | 'profileEnd' | 'count' | 'timeEnd' | 'verbose';
1108
1109/**
1110 * @public
1111 */
1112export declare interface ContinueRequestOverrides {
1113 /**
1114 * If set, the request URL will change. This is not a redirect.
1115 */
1116 url?: string;
1117 method?: string;
1118 postData?: string;
1119 headers?: Record<string, string>;
1120}
1121
1122/**
1123 * The Coverage class provides methods to gathers information about parts of
1124 * JavaScript and CSS that were used by the page.
1125 *
1126 * @remarks
1127 * To output coverage in a form consumable by {@link https://github.com/istanbuljs | Istanbul},
1128 * see {@link https://github.com/istanbuljs/puppeteer-to-istanbul | puppeteer-to-istanbul}.
1129 *
1130 * @example
1131 * An example of using JavaScript and CSS coverage to get percentage of initially
1132 * executed code:
1133 *
1134 * ```ts
1135 * // Enable both JavaScript and CSS coverage
1136 * await Promise.all([
1137 * page.coverage.startJSCoverage(),
1138 * page.coverage.startCSSCoverage(),
1139 * ]);
1140 * // Navigate to page
1141 * await page.goto('https://example.com');
1142 * // Disable both JavaScript and CSS coverage
1143 * const [jsCoverage, cssCoverage] = await Promise.all([
1144 * page.coverage.stopJSCoverage(),
1145 * page.coverage.stopCSSCoverage(),
1146 * ]);
1147 * let totalBytes = 0;
1148 * let usedBytes = 0;
1149 * const coverage = [...jsCoverage, ...cssCoverage];
1150 * for (const entry of coverage) {
1151 * totalBytes += entry.text.length;
1152 * for (const range of entry.ranges) usedBytes += range.end - range.start - 1;
1153 * }
1154 * console.log(`Bytes used: ${(usedBytes / totalBytes) * 100}%`);
1155 * ```
1156 *
1157 * @public
1158 */
1159export declare class Coverage {
1160 #private;
1161 constructor(client: CDPSession);
1162 /**
1163 * @param options - Set of configurable options for coverage defaults to
1164 * `resetOnNavigation : true, reportAnonymousScripts : false,`
1165 * `includeRawScriptCoverage : false, useBlockCoverage : true`
1166 * @returns Promise that resolves when coverage is started.
1167 *
1168 * @remarks
1169 * Anonymous scripts are ones that don't have an associated url. These are
1170 * scripts that are dynamically created on the page using `eval` or
1171 * `new Function`. If `reportAnonymousScripts` is set to `true`, anonymous
1172 * scripts URL will start with `debugger://VM` (unless a magic //# sourceURL
1173 * comment is present, in which case that will the be URL).
1174 */
1175 startJSCoverage(options?: JSCoverageOptions): Promise<void>;
1176 /**
1177 * @returns Promise that resolves to the array of coverage reports for
1178 * all scripts.
1179 *
1180 * @remarks
1181 * JavaScript Coverage doesn't include anonymous scripts by default.
1182 * However, scripts with sourceURLs are reported.
1183 */
1184 stopJSCoverage(): Promise<JSCoverageEntry[]>;
1185 /**
1186 * @param options - Set of configurable options for coverage, defaults to
1187 * `resetOnNavigation : true`
1188 * @returns Promise that resolves when coverage is started.
1189 */
1190 startCSSCoverage(options?: CSSCoverageOptions): Promise<void>;
1191 /**
1192 * @returns Promise that resolves to the array of coverage reports
1193 * for all stylesheets.
1194 * @remarks
1195 * CSS Coverage doesn't include dynamically injected style tags
1196 * without sourceURLs.
1197 */
1198 stopCSSCoverage(): Promise<CoverageEntry[]>;
1199}
1200
1201/**
1202 * The CoverageEntry class represents one entry of the coverage report.
1203 * @public
1204 */
1205export declare interface CoverageEntry {
1206 /**
1207 * The URL of the style sheet or script.
1208 */
1209 url: string;
1210 /**
1211 * The content of the style sheet or script.
1212 */
1213 text: string;
1214 /**
1215 * The covered range as start and end positions.
1216 */
1217 ranges: Array<{
1218 start: number;
1219 end: number;
1220 }>;
1221}
1222
1223export declare const createBrowserFetcher: (options?: Partial<BrowserFetcherOptions> | undefined) => BrowserFetcher;
1224
1225/* Excluded from this release type: createDebuggableDeferredPromise */
1226
1227/* Excluded from this release type: createDeferredPromise */
1228
1229/* Excluded from this release type: createJSHandle */
1230
1231/**
1232 * @public
1233 */
1234export declare interface Credentials {
1235 username: string;
1236 password: string;
1237}
1238
1239/**
1240 * @public
1241 */
1242export declare class CSSCoverage {
1243 #private;
1244 constructor(client: CDPSession);
1245 start(options?: {
1246 resetOnNavigation?: boolean;
1247 }): Promise<void>;
1248 stop(): Promise<CoverageEntry[]>;
1249}
1250
1251/**
1252 * Set of configurable options for CSS coverage.
1253 * @public
1254 */
1255export declare interface CSSCoverageOptions {
1256 /**
1257 * Whether to reset coverage on every navigation.
1258 */
1259 resetOnNavigation?: boolean;
1260}
1261
1262/**
1263 * Copyright 2018 Google Inc. All rights reserved.
1264 *
1265 * Licensed under the Apache License, Version 2.0 (the "License");
1266 * you may not use this file except in compliance with the License.
1267 * You may obtain a copy of the License at
1268 *
1269 * http://www.apache.org/licenses/LICENSE-2.0
1270 *
1271 * Unless required by applicable law or agreed to in writing, software
1272 * distributed under the License is distributed on an "AS IS" BASIS,
1273 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1274 * See the License for the specific language governing permissions and
1275 * limitations under the License.
1276 */
1277/**
1278 * @deprecated Do not use.
1279 *
1280 * @public
1281 */
1282export declare class CustomError extends Error {
1283 /* Excluded from this release type: __constructor */
1284}
1285
1286/**
1287 * @public
1288 */
1289export declare interface CustomQueryHandler {
1290 /**
1291 * @returns A {@link Node} matching the given `selector` from {@link node}.
1292 */
1293 queryOne?: (node: Node, selector: string) => Node | null;
1294 /**
1295 * @returns Some {@link Node}s matching the given `selector` from {@link node}.
1296 */
1297 queryAll?: (node: Node, selector: string) => Node[];
1298}
1299
1300/**
1301 * @deprecated Import {@link Puppeteer} and use the static method
1302 * {@link Puppeteer.customQueryHandlerNames}
1303 *
1304 * @public
1305 */
1306export declare function customQueryHandlerNames(): string[];
1307
1308/* Excluded from this release type: debug_2 */
1309
1310/* Excluded from this release type: debugError */
1311
1312/**
1313 * The default cooperative request interception resolution priority
1314 *
1315 * @public
1316 */
1317export declare const DEFAULT_INTERCEPT_RESOLUTION_PRIORITY = 0;
1318
1319export declare const defaultArgs: (options?: BrowserLaunchArgumentOptions | undefined) => string[];
1320
1321/* Excluded from this release type: DeferredPromise */
1322
1323/* Excluded from this release type: DeferredPromiseOptions */
1324
1325/**
1326 * @public
1327 */
1328export declare interface Device {
1329 userAgent: string;
1330 viewport: Viewport;
1331}
1332
1333/**
1334 * @deprecated Import {@link KnownDevices}
1335 *
1336 * @public
1337 */
1338export declare const devices: Readonly<Record<"Blackberry PlayBook" | "Blackberry PlayBook landscape" | "BlackBerry Z30" | "BlackBerry Z30 landscape" | "Galaxy Note 3" | "Galaxy Note 3 landscape" | "Galaxy Note II" | "Galaxy Note II landscape" | "Galaxy S III" | "Galaxy S III landscape" | "Galaxy S5" | "Galaxy S5 landscape" | "Galaxy S8" | "Galaxy S8 landscape" | "Galaxy S9+" | "Galaxy S9+ landscape" | "Galaxy Tab S4" | "Galaxy Tab S4 landscape" | "iPad" | "iPad landscape" | "iPad (gen 6)" | "iPad (gen 6) landscape" | "iPad (gen 7)" | "iPad (gen 7) landscape" | "iPad Mini" | "iPad Mini landscape" | "iPad Pro" | "iPad Pro landscape" | "iPad Pro 11" | "iPad Pro 11 landscape" | "iPhone 4" | "iPhone 4 landscape" | "iPhone 5" | "iPhone 5 landscape" | "iPhone 6" | "iPhone 6 landscape" | "iPhone 6 Plus" | "iPhone 6 Plus landscape" | "iPhone 7" | "iPhone 7 landscape" | "iPhone 7 Plus" | "iPhone 7 Plus landscape" | "iPhone 8" | "iPhone 8 landscape" | "iPhone 8 Plus" | "iPhone 8 Plus landscape" | "iPhone SE" | "iPhone SE landscape" | "iPhone X" | "iPhone X landscape" | "iPhone XR" | "iPhone XR landscape" | "iPhone 11" | "iPhone 11 landscape" | "iPhone 11 Pro" | "iPhone 11 Pro landscape" | "iPhone 11 Pro Max" | "iPhone 11 Pro Max landscape" | "iPhone 12" | "iPhone 12 landscape" | "iPhone 12 Pro" | "iPhone 12 Pro landscape" | "iPhone 12 Pro Max" | "iPhone 12 Pro Max landscape" | "iPhone 12 Mini" | "iPhone 12 Mini landscape" | "iPhone 13" | "iPhone 13 landscape" | "iPhone 13 Pro" | "iPhone 13 Pro landscape" | "iPhone 13 Pro Max" | "iPhone 13 Pro Max landscape" | "iPhone 13 Mini" | "iPhone 13 Mini landscape" | "JioPhone 2" | "JioPhone 2 landscape" | "Kindle Fire HDX" | "Kindle Fire HDX landscape" | "LG Optimus L70" | "LG Optimus L70 landscape" | "Microsoft Lumia 550" | "Microsoft Lumia 950" | "Microsoft Lumia 950 landscape" | "Nexus 10" | "Nexus 10 landscape" | "Nexus 4" | "Nexus 4 landscape" | "Nexus 5" | "Nexus 5 landscape" | "Nexus 5X" | "Nexus 5X landscape" | "Nexus 6" | "Nexus 6 landscape" | "Nexus 6P" | "Nexus 6P landscape" | "Nexus 7" | "Nexus 7 landscape" | "Nokia Lumia 520" | "Nokia Lumia 520 landscape" | "Nokia N9" | "Nokia N9 landscape" | "Pixel 2" | "Pixel 2 landscape" | "Pixel 2 XL" | "Pixel 2 XL landscape" | "Pixel 3" | "Pixel 3 landscape" | "Pixel 4" | "Pixel 4 landscape" | "Pixel 4a (5G)" | "Pixel 4a (5G) landscape" | "Pixel 5" | "Pixel 5 landscape" | "Moto G4" | "Moto G4 landscape", Device>>;
1339
1340/**
1341 * Dialog instances are dispatched by the {@link Page} via the `dialog` event.
1342 *
1343 * @remarks
1344 *
1345 * @example
1346 *
1347 * ```ts
1348 * import puppeteer from 'puppeteer';
1349 *
1350 * (async () => {
1351 * const browser = await puppeteer.launch();
1352 * const page = await browser.newPage();
1353 * page.on('dialog', async dialog => {
1354 * console.log(dialog.message());
1355 * await dialog.dismiss();
1356 * await browser.close();
1357 * });
1358 * page.evaluate(() => alert('1'));
1359 * })();
1360 * ```
1361 *
1362 * @public
1363 */
1364export declare class Dialog {
1365 #private;
1366 /* Excluded from this release type: __constructor */
1367 /**
1368 * @returns The type of the dialog.
1369 */
1370 type(): Protocol.Page.DialogType;
1371 /**
1372 * @returns The message displayed in the dialog.
1373 */
1374 message(): string;
1375 /**
1376 * @returns The default value of the prompt, or an empty string if the dialog
1377 * is not a `prompt`.
1378 */
1379 defaultValue(): string;
1380 /**
1381 * @param promptText - optional text that will be entered in the dialog
1382 * prompt. Has no effect if the dialog's type is not `prompt`.
1383 *
1384 * @returns A promise that resolves when the dialog has been accepted.
1385 */
1386 accept(promptText?: string): Promise<void>;
1387 /**
1388 * @returns A promise which will resolve once the dialog has been dismissed
1389 */
1390 dismiss(): Promise<void>;
1391}
1392
1393declare type Drop<Arr extends readonly unknown[], Remove, Acc extends unknown[] = []> = Arr extends [infer Head, ...infer Tail] ? Head extends Remove ? Drop<Tail, Remove> : Drop<Tail, Remove, [...Acc, Head]> : Acc;
1394
1395/**
1396 * @public
1397 */
1398export declare type ElementFor<TagName extends keyof HTMLElementTagNameMap | keyof SVGElementTagNameMap> = TagName extends keyof HTMLElementTagNameMap ? HTMLElementTagNameMap[TagName] : TagName extends keyof SVGElementTagNameMap ? SVGElementTagNameMap[TagName] : never;
1399
1400/**
1401 * ElementHandle represents an in-page DOM element.
1402 *
1403 * @remarks
1404 * ElementHandles can be created with the {@link Page.$} method.
1405 *
1406 * ```ts
1407 * import puppeteer from 'puppeteer';
1408 *
1409 * (async () => {
1410 * const browser = await puppeteer.launch();
1411 * const page = await browser.newPage();
1412 * await page.goto('https://example.com');
1413 * const hrefElement = await page.$('a');
1414 * await hrefElement.click();
1415 * // ...
1416 * })();
1417 * ```
1418 *
1419 * ElementHandle prevents the DOM element from being garbage-collected unless the
1420 * handle is {@link JSHandle.dispose | disposed}. ElementHandles are auto-disposed
1421 * when their origin frame gets navigated.
1422 *
1423 * ElementHandle instances can be used as arguments in {@link Page.$eval} and
1424 * {@link Page.evaluate} methods.
1425 *
1426 * If you're using TypeScript, ElementHandle takes a generic argument that
1427 * denotes the type of element the handle is holding within. For example, if you
1428 * have a handle to a `<select>` element, you can type it as
1429 * `ElementHandle<HTMLSelectElement>` and you get some nicer type checks.
1430 *
1431 * @public
1432 */
1433export declare class ElementHandle<ElementType extends Node = Element> extends JSHandle<ElementType> {
1434 #private;
1435 /* Excluded from this release type: __constructor */
1436 get frame(): Frame;
1437 /**
1438 * Queries the current element for an element matching the given selector.
1439 *
1440 * @param selector - The selector to query for.
1441 * @returns A {@link ElementHandle | element handle} to the first element
1442 * matching the given selector. Otherwise, `null`.
1443 */
1444 $<Selector extends string>(selector: Selector): Promise<ElementHandle<NodeFor<Selector>> | null>;
1445 /**
1446 * Queries the current element for all elements matching the given selector.
1447 *
1448 * @param selector - The selector to query for.
1449 * @returns An array of {@link ElementHandle | element handles} that point to
1450 * elements matching the given selector.
1451 */
1452 $$<Selector extends string>(selector: Selector): Promise<Array<ElementHandle<NodeFor<Selector>>>>;
1453 /**
1454 * Runs the given function on the first element matching the given selector in
1455 * the current element.
1456 *
1457 * If the given function returns a promise, then this method will wait till
1458 * the promise resolves.
1459 *
1460 * @example
1461 *
1462 * ```ts
1463 * const tweetHandle = await page.$('.tweet');
1464 * expect(await tweetHandle.$eval('.like', node => node.innerText)).toBe(
1465 * '100'
1466 * );
1467 * expect(await tweetHandle.$eval('.retweets', node => node.innerText)).toBe(
1468 * '10'
1469 * );
1470 * ```
1471 *
1472 * @param selector - The selector to query for.
1473 * @param pageFunction - The function to be evaluated in this element's page's
1474 * context. The first element matching the selector will be passed in as the
1475 * first argument.
1476 * @param args - Additional arguments to pass to `pageFunction`.
1477 * @returns A promise to the result of the function.
1478 */
1479 $eval<Selector extends string, Params extends unknown[], Func extends EvaluateFunc<[
1480 ElementHandle<NodeFor<Selector>>,
1481 ...Params
1482 ]> = EvaluateFunc<[ElementHandle<NodeFor<Selector>>, ...Params]>>(selector: Selector, pageFunction: Func | string, ...args: Params): Promise<Awaited<ReturnType<Func>>>;
1483 /**
1484 * Runs the given function on an array of elements matching the given selector
1485 * in the current element.
1486 *
1487 * If the given function returns a promise, then this method will wait till
1488 * the promise resolves.
1489 *
1490 * @example
1491 * HTML:
1492 *
1493 * ```html
1494 * <div class="feed">
1495 * <div class="tweet">Hello!</div>
1496 * <div class="tweet">Hi!</div>
1497 * </div>
1498 * ```
1499 *
1500 * JavaScript:
1501 *
1502 * ```js
1503 * const feedHandle = await page.$('.feed');
1504 * expect(
1505 * await feedHandle.$$eval('.tweet', nodes => nodes.map(n => n.innerText))
1506 * ).toEqual(['Hello!', 'Hi!']);
1507 * ```
1508 *
1509 * @param selector - The selector to query for.
1510 * @param pageFunction - The function to be evaluated in the element's page's
1511 * context. An array of elements matching the given selector will be passed to
1512 * the function as its first argument.
1513 * @param args - Additional arguments to pass to `pageFunction`.
1514 * @returns A promise to the result of the function.
1515 */
1516 $$eval<Selector extends string, Params extends unknown[], Func extends EvaluateFunc<[
1517 HandleFor<Array<NodeFor<Selector>>>,
1518 ...Params
1519 ]> = EvaluateFunc<[HandleFor<Array<NodeFor<Selector>>>, ...Params]>>(selector: Selector, pageFunction: Func | string, ...args: Params): Promise<Awaited<ReturnType<Func>>>;
1520 /**
1521 * @deprecated Use {@link ElementHandle.$$} with the `xpath` prefix.
1522 *
1523 * Example: `await elementHandle.$$('xpath/' + xpathExpression)`
1524 *
1525 * The method evaluates the XPath expression relative to the elementHandle.
1526 * If `xpath` starts with `//` instead of `.//`, the dot will be appended
1527 * automatically.
1528 *
1529 * If there are no such elements, the method will resolve to an empty array.
1530 * @param expression - Expression to {@link https://developer.mozilla.org/en-US/docs/Web/API/Document/evaluate | evaluate}
1531 */
1532 $x(expression: string): Promise<Array<ElementHandle<Node>>>;
1533 /**
1534 * Wait for an element matching the given selector to appear in the current
1535 * element.
1536 *
1537 * Unlike {@link Frame.waitForSelector}, this method does not work across
1538 * navigations or if the element is detached from DOM.
1539 *
1540 * @example
1541 *
1542 * ```ts
1543 * import puppeteer from 'puppeteer';
1544 *
1545 * (async () => {
1546 * const browser = await puppeteer.launch();
1547 * const page = await browser.newPage();
1548 * let currentURL;
1549 * page
1550 * .mainFrame()
1551 * .waitForSelector('img')
1552 * .then(() => console.log('First URL with image: ' + currentURL));
1553 *
1554 * for (currentURL of [
1555 * 'https://example.com',
1556 * 'https://google.com',
1557 * 'https://bbc.com',
1558 * ]) {
1559 * await page.goto(currentURL);
1560 * }
1561 * await browser.close();
1562 * })();
1563 * ```
1564 *
1565 * @param selector - The selector to query and wait for.
1566 * @param options - Options for customizing waiting behavior.
1567 * @returns An element matching the given selector.
1568 * @throws Throws if an element matching the given selector doesn't appear.
1569 */
1570 waitForSelector<Selector extends string>(selector: Selector, options?: WaitForSelectorOptions): Promise<ElementHandle<NodeFor<Selector>> | null>;
1571 /**
1572 * @deprecated Use {@link ElementHandle.waitForSelector} with the `xpath`
1573 * prefix.
1574 *
1575 * Example: `await elementHandle.waitForSelector('xpath/' + xpathExpression)`
1576 *
1577 * The method evaluates the XPath expression relative to the elementHandle.
1578 *
1579 * Wait for the `xpath` within the element. If at the moment of calling the
1580 * method the `xpath` already exists, the method will return immediately. If
1581 * the `xpath` doesn't appear after the `timeout` milliseconds of waiting, the
1582 * function will throw.
1583 *
1584 * If `xpath` starts with `//` instead of `.//`, the dot will be appended
1585 * automatically.
1586 *
1587 * This method works across navigation.
1588 *
1589 * ```ts
1590 * import puppeteer from 'puppeteer';
1591 * (async () => {
1592 * const browser = await puppeteer.launch();
1593 * const page = await browser.newPage();
1594 * let currentURL;
1595 * page
1596 * .waitForXPath('//img')
1597 * .then(() => console.log('First URL with image: ' + currentURL));
1598 * for (currentURL of [
1599 * 'https://example.com',
1600 * 'https://google.com',
1601 * 'https://bbc.com',
1602 * ]) {
1603 * await page.goto(currentURL);
1604 * }
1605 * await browser.close();
1606 * })();
1607 * ```
1608 *
1609 * @param xpath - A
1610 * {@link https://developer.mozilla.org/en-US/docs/Web/XPath | xpath} of an
1611 * element to wait for
1612 * @param options - Optional waiting parameters
1613 * @returns Promise which resolves when element specified by xpath string is
1614 * added to DOM. Resolves to `null` if waiting for `hidden: true` and xpath is
1615 * not found in DOM.
1616 * @remarks
1617 * The optional Argument `options` have properties:
1618 *
1619 * - `visible`: A boolean to wait for element to be present in DOM and to be
1620 * visible, i.e. to not have `display: none` or `visibility: hidden` CSS
1621 * properties. Defaults to `false`.
1622 *
1623 * - `hidden`: A boolean wait for element to not be found in the DOM or to be
1624 * hidden, i.e. have `display: none` or `visibility: hidden` CSS properties.
1625 * Defaults to `false`.
1626 *
1627 * - `timeout`: A number which is maximum time to wait for in milliseconds.
1628 * Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
1629 * default value can be changed by using the {@link Page.setDefaultTimeout}
1630 * method.
1631 */
1632 waitForXPath(xpath: string, options?: {
1633 visible?: boolean;
1634 hidden?: boolean;
1635 timeout?: number;
1636 }): Promise<ElementHandle<Node> | null>;
1637 /**
1638 * Converts the current handle to the given element type.
1639 *
1640 * @example
1641 *
1642 * ```ts
1643 * const element: ElementHandle<Element> = await page.$(
1644 * '.class-name-of-anchor'
1645 * );
1646 * // DO NOT DISPOSE `element`, this will be always be the same handle.
1647 * const anchor: ElementHandle<HTMLAnchorElement> = await element.toElement(
1648 * 'a'
1649 * );
1650 * ```
1651 *
1652 * @param tagName - The tag name of the desired element type.
1653 * @throws An error if the handle does not match. **The handle will not be
1654 * automatically disposed.**
1655 */
1656 toElement<K extends keyof HTMLElementTagNameMap | keyof SVGElementTagNameMap>(tagName: K): Promise<HandleFor<ElementFor<K>>>;
1657 asElement(): ElementHandle<ElementType> | null;
1658 /**
1659 * Resolves to the content frame for element handles referencing
1660 * iframe nodes, or null otherwise
1661 */
1662 contentFrame(): Promise<Frame | null>;
1663 /**
1664 * Returns the middle point within an element unless a specific offset is provided.
1665 */
1666 clickablePoint(offset?: Offset): Promise<Point>;
1667 /**
1668 * This method scrolls element into view if needed, and then
1669 * uses {@link Page.mouse} to hover over the center of the element.
1670 * If the element is detached from DOM, the method throws an error.
1671 */
1672 hover(this: ElementHandle<Element>): Promise<void>;
1673 /**
1674 * This method scrolls element into view if needed, and then
1675 * uses {@link Page.mouse} to click in the center of the element.
1676 * If the element is detached from DOM, the method throws an error.
1677 */
1678 click(this: ElementHandle<Element>, options?: ClickOptions): Promise<void>;
1679 /**
1680 * This method creates and captures a dragevent from the element.
1681 */
1682 drag(this: ElementHandle<Element>, target: Point): Promise<Protocol.Input.DragData>;
1683 /**
1684 * This method creates a `dragenter` event on the element.
1685 */
1686 dragEnter(this: ElementHandle<Element>, data?: Protocol.Input.DragData): Promise<void>;
1687 /**
1688 * This method creates a `dragover` event on the element.
1689 */
1690 dragOver(this: ElementHandle<Element>, data?: Protocol.Input.DragData): Promise<void>;
1691 /**
1692 * This method triggers a drop on the element.
1693 */
1694 drop(this: ElementHandle<Element>, data?: Protocol.Input.DragData): Promise<void>;
1695 /**
1696 * This method triggers a dragenter, dragover, and drop on the element.
1697 */
1698 dragAndDrop(this: ElementHandle<Element>, target: ElementHandle<Node>, options?: {
1699 delay: number;
1700 }): Promise<void>;
1701 /**
1702 * Triggers a `change` and `input` event once all the provided options have been
1703 * selected. If there's no `<select>` element matching `selector`, the method
1704 * throws an error.
1705 *
1706 * @example
1707 *
1708 * ```ts
1709 * handle.select('blue'); // single selection
1710 * handle.select('red', 'green', 'blue'); // multiple selections
1711 * ```
1712 *
1713 * @param values - Values of options to select. If the `<select>` has the
1714 * `multiple` attribute, all values are considered, otherwise only the first
1715 * one is taken into account.
1716 */
1717 select(...values: string[]): Promise<string[]>;
1718 /**
1719 * This method expects `elementHandle` to point to an
1720 * {@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input | input element}.
1721 *
1722 * @param filePaths - Sets the value of the file input to these paths.
1723 * If a path is relative, then it is resolved against the
1724 * {@link https://nodejs.org/api/process.html#process_process_cwd | current working directory}.
1725 * Note for locals script connecting to remote chrome environments,
1726 * paths must be absolute.
1727 */
1728 uploadFile(this: ElementHandle<HTMLInputElement>, ...filePaths: string[]): Promise<void>;
1729 /**
1730 * This method scrolls element into view if needed, and then uses
1731 * {@link Touchscreen.tap} to tap in the center of the element.
1732 * If the element is detached from DOM, the method throws an error.
1733 */
1734 tap(this: ElementHandle<Element>): Promise<void>;
1735 /**
1736 * Calls {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus | focus} on the element.
1737 */
1738 focus(): Promise<void>;
1739 /**
1740 * Focuses the element, and then sends a `keydown`, `keypress`/`input`, and
1741 * `keyup` event for each character in the text.
1742 *
1743 * To press a special key, like `Control` or `ArrowDown`,
1744 * use {@link ElementHandle.press}.
1745 *
1746 * @example
1747 *
1748 * ```ts
1749 * await elementHandle.type('Hello'); // Types instantly
1750 * await elementHandle.type('World', {delay: 100}); // Types slower, like a user
1751 * ```
1752 *
1753 * @example
1754 * An example of typing into a text field and then submitting the form:
1755 *
1756 * ```ts
1757 * const elementHandle = await page.$('input');
1758 * await elementHandle.type('some text');
1759 * await elementHandle.press('Enter');
1760 * ```
1761 */
1762 type(text: string, options?: {
1763 delay: number;
1764 }): Promise<void>;
1765 /**
1766 * Focuses the element, and then uses {@link Keyboard.down} and {@link Keyboard.up}.
1767 *
1768 * @remarks
1769 * If `key` is a single character and no modifier keys besides `Shift`
1770 * are being held down, a `keypress`/`input` event will also be generated.
1771 * The `text` option can be specified to force an input event to be generated.
1772 *
1773 * **NOTE** Modifier keys DO affect `elementHandle.press`. Holding down `Shift`
1774 * will type the text in upper case.
1775 *
1776 * @param key - Name of key to press, such as `ArrowLeft`.
1777 * See {@link KeyInput} for a list of all key names.
1778 */
1779 press(key: KeyInput, options?: PressOptions): Promise<void>;
1780 /**
1781 * This method returns the bounding box of the element (relative to the main frame),
1782 * or `null` if the element is not visible.
1783 */
1784 boundingBox(): Promise<BoundingBox | null>;
1785 /**
1786 * This method returns boxes of the element, or `null` if the element is not visible.
1787 *
1788 * @remarks
1789 *
1790 * Boxes are represented as an array of points;
1791 * Each Point is an object `{x, y}`. Box points are sorted clock-wise.
1792 */
1793 boxModel(): Promise<BoxModel | null>;
1794 /**
1795 * This method scrolls element into view if needed, and then uses
1796 * {@link Page.screenshot} to take a screenshot of the element.
1797 * If the element is detached from DOM, the method throws an error.
1798 */
1799 screenshot(this: ElementHandle<Element>, options?: ScreenshotOptions): Promise<string | Buffer>;
1800 /**
1801 * Resolves to true if the element is visible in the current viewport.
1802 */
1803 isIntersectingViewport(this: ElementHandle<Element>, options?: {
1804 threshold?: number;
1805 }): Promise<boolean>;
1806}
1807
1808/* Excluded from this release type: EmulationManager */
1809
1810/**
1811 * @public
1812 */
1813export declare type ErrorCode = 'aborted' | 'accessdenied' | 'addressunreachable' | 'blockedbyclient' | 'blockedbyresponse' | 'connectionaborted' | 'connectionclosed' | 'connectionfailed' | 'connectionrefused' | 'connectionreset' | 'internetdisconnected' | 'namenotresolved' | 'timedout' | 'failed';
1814
1815/* Excluded from this release type: ErrorLike */
1816
1817/**
1818 * @deprecated Import error classes directly.
1819 *
1820 * Puppeteer methods might throw errors if they are unable to fulfill a request.
1821 * For example, `page.waitForSelector(selector[, options])` might fail if the
1822 * selector doesn't match any nodes during the given timeframe.
1823 *
1824 * For certain types of errors Puppeteer uses specific error classes. These
1825 * classes are available via `puppeteer.errors`.
1826 *
1827 * @example
1828 * An example of handling a timeout error:
1829 *
1830 * ```ts
1831 * try {
1832 * await page.waitForSelector('.foo');
1833 * } catch (e) {
1834 * if (e instanceof TimeoutError) {
1835 * // Do something if this is a timeout.
1836 * }
1837 * }
1838 * ```
1839 *
1840 * @public
1841 */
1842export declare const errors: PuppeteerErrors;
1843
1844/**
1845 * @public
1846 */
1847export declare type EvaluateFunc<T extends unknown[]> = (...params: InnerParams<T>) => Awaitable<unknown>;
1848
1849/**
1850 * @public
1851 */
1852export declare const EVALUATION_SCRIPT_URL = "pptr://__puppeteer_evaluation_script__";
1853
1854/* Excluded from this release type: evaluationString */
1855
1856/**
1857 * The EventEmitter class that many Puppeteer classes extend.
1858 *
1859 * @remarks
1860 *
1861 * This allows you to listen to events that Puppeteer classes fire and act
1862 * accordingly. Therefore you'll mostly use {@link EventEmitter.on | on} and
1863 * {@link EventEmitter.off | off} to bind
1864 * and unbind to event listeners.
1865 *
1866 * @public
1867 */
1868export declare class EventEmitter implements CommonEventEmitter {
1869 private emitter;
1870 private eventsMap;
1871 /* Excluded from this release type: __constructor */
1872 /**
1873 * Bind an event listener to fire when an event occurs.
1874 * @param event - the event type you'd like to listen to. Can be a string or symbol.
1875 * @param handler - the function to be called when the event occurs.
1876 * @returns `this` to enable you to chain method calls.
1877 */
1878 on(event: EventType, handler: Handler<any>): EventEmitter;
1879 /**
1880 * Remove an event listener from firing.
1881 * @param event - the event type you'd like to stop listening to.
1882 * @param handler - the function that should be removed.
1883 * @returns `this` to enable you to chain method calls.
1884 */
1885 off(event: EventType, handler: Handler<any>): EventEmitter;
1886 /**
1887 * Remove an event listener.
1888 * @deprecated please use {@link EventEmitter.off} instead.
1889 */
1890 removeListener(event: EventType, handler: Handler<any>): EventEmitter;
1891 /**
1892 * Add an event listener.
1893 * @deprecated please use {@link EventEmitter.on} instead.
1894 */
1895 addListener(event: EventType, handler: Handler<any>): EventEmitter;
1896 /**
1897 * Emit an event and call any associated listeners.
1898 *
1899 * @param event - the event you'd like to emit
1900 * @param eventData - any data you'd like to emit with the event
1901 * @returns `true` if there are any listeners, `false` if there are not.
1902 */
1903 emit(event: EventType, eventData?: unknown): boolean;
1904 /**
1905 * Like `on` but the listener will only be fired once and then it will be removed.
1906 * @param event - the event you'd like to listen to
1907 * @param handler - the handler function to run when the event occurs
1908 * @returns `this` to enable you to chain method calls.
1909 */
1910 once(event: EventType, handler: Handler<any>): EventEmitter;
1911 /**
1912 * Gets the number of listeners for a given event.
1913 *
1914 * @param event - the event to get the listener count for
1915 * @returns the number of listeners bound to the given event
1916 */
1917 listenerCount(event: EventType): number;
1918 /**
1919 * Removes all listeners. If given an event argument, it will remove only
1920 * listeners for that event.
1921 * @param event - the event to remove listeners for.
1922 * @returns `this` to enable you to chain method calls.
1923 */
1924 removeAllListeners(event?: EventType): EventEmitter;
1925 private eventListenersCount;
1926}
1927
1928/**
1929 * Copyright 2022 Google Inc. All rights reserved.
1930 *
1931 * Licensed under the Apache License, Version 2.0 (the "License");
1932 * you may not use this file except in compliance with the License.
1933 * You may obtain a copy of the License at
1934 *
1935 * http://www.apache.org/licenses/LICENSE-2.0
1936 *
1937 * Unless required by applicable law or agreed to in writing, software
1938 * distributed under the License is distributed on an "AS IS" BASIS,
1939 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1940 * See the License for the specific language governing permissions and
1941 * limitations under the License.
1942 */
1943/**
1944 * @public
1945 */
1946export declare type EventType = string | symbol;
1947
1948/* Excluded from this release type: ExceptionThrownCallback */
1949
1950export declare const executablePath: (channel?: ChromeReleaseChannel | undefined) => string;
1951
1952/* Excluded from this release type: ExecutionContext */
1953
1954/**
1955 * Defines experiment options for Puppeteer.
1956 *
1957 * See individual properties for more information.
1958 *
1959 * @public
1960 */
1961export declare interface ExperimentsConfiguration {
1962 /**
1963 * Require Puppeteer to download Chromium for Apple M1.
1964 *
1965 * On Apple M1 devices Puppeteer by default downloads the version for
1966 * Intel's processor which runs via Rosetta. It works without any problems,
1967 * however, with this option, you should get more efficient resource usage
1968 * (CPU and RAM) that could lead to a faster execution time.
1969 *
1970 * Can be overridden by `PUPPETEER_EXPERIMENTAL_CHROMIUM_MAC_ARM`.
1971 *
1972 * @defaultValue `false`
1973 */
1974 macArmChromiumEnabled?: boolean;
1975}
1976
1977/* Excluded from this release type: FetchRequestId */
1978
1979/**
1980 * File choosers let you react to the page requesting for a file.
1981 *
1982 * @remarks
1983 * `FileChooser` instances are returned via the {@link Page.waitForFileChooser} method.
1984 *
1985 * In browsers, only one file chooser can be opened at a time.
1986 * All file choosers must be accepted or canceled. Not doing so will prevent
1987 * subsequent file choosers from appearing.
1988 *
1989 * @example
1990 *
1991 * ```ts
1992 * const [fileChooser] = await Promise.all([
1993 * page.waitForFileChooser(),
1994 * page.click('#upload-file-button'), // some button that triggers file selection
1995 * ]);
1996 * await fileChooser.accept(['/tmp/myfile.pdf']);
1997 * ```
1998 *
1999 * @public
2000 */
2001export declare class FileChooser {
2002 #private;
2003 /* Excluded from this release type: __constructor */
2004 /**
2005 * Whether file chooser allow for
2006 * {@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file#attr-multiple | multiple}
2007 * file selection.
2008 */
2009 isMultiple(): boolean;
2010 /**
2011 * Accept the file chooser request with given paths.
2012 *
2013 * @param filePaths - If some of the `filePaths` are relative paths, then
2014 * they are resolved relative to the
2015 * {@link https://nodejs.org/api/process.html#process_process_cwd | current working directory}.
2016 */
2017 accept(filePaths: string[]): Promise<void>;
2018 /**
2019 * Closes the file chooser without selecting any files.
2020 */
2021 cancel(): void;
2022}
2023
2024/* Excluded from this release type: FirefoxLauncher */
2025
2026/* Excluded from this release type: FirefoxTargetManager */
2027
2028declare type FlatmapSplitWithDelemiters<Inputs extends readonly string[], Delemiters extends readonly string[], Acc extends string[] = []> = Inputs extends [infer FirstInput, ...infer RestInputs] ? FirstInput extends string ? RestInputs extends readonly string[] ? FlatmapSplitWithDelemiters<RestInputs, Delemiters, [
2029...Acc,
2030...SplitWithDelemiters<FirstInput, Delemiters>
2031]> : Acc : Acc : Acc;
2032
2033/**
2034 * @public
2035 */
2036export declare type FlattenHandle<T> = T extends HandleOr<infer U> ? U : never;
2037
2038/* Excluded from this release type: FlattenLazyArg */
2039
2040/**
2041 * Represents a DOM frame.
2042 *
2043 * To understand frames, you can think of frames as `<iframe>` elements. Just
2044 * like iframes, frames can be nested, and when JavaScript is executed in a
2045 * frame, the JavaScript does not effect frames inside the ambient frame the
2046 * JavaScript executes in.
2047 *
2048 * @example
2049 * At any point in time, {@link Page | pages} expose their current frame
2050 * tree via the {@link Page.mainFrame} and {@link Frame.childFrames} methods.
2051 *
2052 * @example
2053 * An example of dumping frame tree:
2054 *
2055 * ```ts
2056 * import puppeteer from 'puppeteer';
2057 *
2058 * (async () => {
2059 * const browser = await puppeteer.launch();
2060 * const page = await browser.newPage();
2061 * await page.goto('https://www.google.com/chrome/browser/canary.html');
2062 * dumpFrameTree(page.mainFrame(), '');
2063 * await browser.close();
2064 *
2065 * function dumpFrameTree(frame, indent) {
2066 * console.log(indent + frame.url());
2067 * for (const child of frame.childFrames()) {
2068 * dumpFrameTree(child, indent + ' ');
2069 * }
2070 * }
2071 * })();
2072 * ```
2073 *
2074 * @example
2075 * An example of getting text from an iframe element:
2076 *
2077 * ```ts
2078 * const frame = page.frames().find(frame => frame.name() === 'myframe');
2079 * const text = await frame.$eval('.selector', element => element.textContent);
2080 * console.log(text);
2081 * ```
2082 *
2083 * @remarks
2084 * Frame lifecycles are controlled by three events that are all dispatched on
2085 * the parent {@link Frame.page | page}:
2086 *
2087 * - {@link PageEmittedEvents.FrameAttached}
2088 * - {@link PageEmittedEvents.FrameNavigated}
2089 * - {@link PageEmittedEvents.FrameDetached}
2090 *
2091 * @public
2092 */
2093export declare class Frame {
2094 #private;
2095 /* Excluded from this release type: worlds */
2096 /* Excluded from this release type: _frameManager */
2097 /* Excluded from this release type: _id */
2098 /* Excluded from this release type: _loaderId */
2099 /* Excluded from this release type: _name */
2100 /* Excluded from this release type: _hasStartedLoading */
2101 /* Excluded from this release type: _lifecycleEvents */
2102 /* Excluded from this release type: _parentId */
2103 /* Excluded from this release type: __constructor */
2104 /* Excluded from this release type: updateClient */
2105 /**
2106 * @returns The page associated with the frame.
2107 */
2108 page(): Page;
2109 /**
2110 * @returns `true` if the frame is an out-of-process (OOP) frame. Otherwise,
2111 * `false`.
2112 */
2113 isOOPFrame(): boolean;
2114 /**
2115 * Navigates a frame to the given url.
2116 *
2117 * @remarks
2118 * Navigation to `about:blank` or navigation to the same URL with a different
2119 * hash will succeed and return `null`.
2120 *
2121 * :::warning
2122 *
2123 * Headless mode doesn't support navigation to a PDF document. See the {@link
2124 * https://bugs.chromium.org/p/chromium/issues/detail?id=761295 | upstream
2125 * issue}.
2126 *
2127 * :::
2128 *
2129 * @param url - the URL to navigate the frame to. This should include the
2130 * scheme, e.g. `https://`.
2131 * @param options - navigation options. `waitUntil` is useful to define when
2132 * the navigation should be considered successful - see the docs for
2133 * {@link PuppeteerLifeCycleEvent} for more details.
2134 *
2135 * @returns A promise which resolves to the main resource response. In case of
2136 * multiple redirects, the navigation will resolve with the response of the
2137 * last redirect.
2138 * @throws This method will throw an error if:
2139 *
2140 * - there's an SSL error (e.g. in case of self-signed certificates).
2141 * - target URL is invalid.
2142 * - the `timeout` is exceeded during navigation.
2143 * - the remote server does not respond or is unreachable.
2144 * - the main resource failed to load.
2145 *
2146 * This method will not throw an error when any valid HTTP status code is
2147 * returned by the remote server, including 404 "Not Found" and 500 "Internal
2148 * Server Error". The status code for such responses can be retrieved by
2149 * calling {@link HTTPResponse.status}.
2150 */
2151 goto(url: string, options?: {
2152 referer?: string;
2153 referrerPolicy?: string;
2154 timeout?: number;
2155 waitUntil?: PuppeteerLifeCycleEvent | PuppeteerLifeCycleEvent[];
2156 }): Promise<HTTPResponse | null>;
2157 /**
2158 * Waits for the frame to navigate. It is useful for when you run code which
2159 * will indirectly cause the frame to navigate.
2160 *
2161 * Usage of the
2162 * {@link https://developer.mozilla.org/en-US/docs/Web/API/History_API | History API}
2163 * to change the URL is considered a navigation.
2164 *
2165 * @example
2166 *
2167 * ```ts
2168 * const [response] = await Promise.all([
2169 * // The navigation promise resolves after navigation has finished
2170 * frame.waitForNavigation(),
2171 * // Clicking the link will indirectly cause a navigation
2172 * frame.click('a.my-link'),
2173 * ]);
2174 * ```
2175 *
2176 * @param options - options to configure when the navigation is consided
2177 * finished.
2178 * @returns a promise that resolves when the frame navigates to a new URL.
2179 */
2180 waitForNavigation(options?: {
2181 timeout?: number;
2182 waitUntil?: PuppeteerLifeCycleEvent | PuppeteerLifeCycleEvent[];
2183 }): Promise<HTTPResponse | null>;
2184 /* Excluded from this release type: _client */
2185 /* Excluded from this release type: executionContext */
2186 /**
2187 * Behaves identically to {@link Page.evaluateHandle} except it's run within
2188 * the context of this frame.
2189 *
2190 * @see {@link Page.evaluateHandle} for details.
2191 */
2192 evaluateHandle<Params extends unknown[], Func extends EvaluateFunc<Params> = EvaluateFunc<Params>>(pageFunction: Func | string, ...args: Params): Promise<HandleFor<Awaited<ReturnType<Func>>>>;
2193 /**
2194 * Behaves identically to {@link Page.evaluate} except it's run within the
2195 * the context of this frame.
2196 *
2197 * @see {@link Page.evaluate} for details.
2198 */
2199 evaluate<Params extends unknown[], Func extends EvaluateFunc<Params> = EvaluateFunc<Params>>(pageFunction: Func | string, ...args: Params): Promise<Awaited<ReturnType<Func>>>;
2200 /**
2201 * Queries the frame for an element matching the given selector.
2202 *
2203 * @param selector - The selector to query for.
2204 * @returns A {@link ElementHandle | element handle} to the first element
2205 * matching the given selector. Otherwise, `null`.
2206 */
2207 $<Selector extends string>(selector: Selector): Promise<ElementHandle<NodeFor<Selector>> | null>;
2208 /**
2209 * Queries the frame for all elements matching the given selector.
2210 *
2211 * @param selector - The selector to query for.
2212 * @returns An array of {@link ElementHandle | element handles} that point to
2213 * elements matching the given selector.
2214 */
2215 $$<Selector extends string>(selector: Selector): Promise<Array<ElementHandle<NodeFor<Selector>>>>;
2216 /**
2217 * Runs the given function on the first element matching the given selector in
2218 * the frame.
2219 *
2220 * If the given function returns a promise, then this method will wait till
2221 * the promise resolves.
2222 *
2223 * @example
2224 *
2225 * ```ts
2226 * const searchValue = await frame.$eval('#search', el => el.value);
2227 * ```
2228 *
2229 * @param selector - The selector to query for.
2230 * @param pageFunction - The function to be evaluated in the frame's context.
2231 * The first element matching the selector will be passed to the function as
2232 * its first argument.
2233 * @param args - Additional arguments to pass to `pageFunction`.
2234 * @returns A promise to the result of the function.
2235 */
2236 $eval<Selector extends string, Params extends unknown[], Func extends EvaluateFunc<[
2237 ElementHandle<NodeFor<Selector>>,
2238 ...Params
2239 ]> = EvaluateFunc<[ElementHandle<NodeFor<Selector>>, ...Params]>>(selector: Selector, pageFunction: Func | string, ...args: Params): Promise<Awaited<ReturnType<Func>>>;
2240 /**
2241 * Runs the given function on an array of elements matching the given selector
2242 * in the frame.
2243 *
2244 * If the given function returns a promise, then this method will wait till
2245 * the promise resolves.
2246 *
2247 * @example
2248 *
2249 * ```js
2250 * const divsCounts = await frame.$$eval('div', divs => divs.length);
2251 * ```
2252 *
2253 * @param selector - The selector to query for.
2254 * @param pageFunction - The function to be evaluated in the frame's context.
2255 * An array of elements matching the given selector will be passed to the
2256 * function as its first argument.
2257 * @param args - Additional arguments to pass to `pageFunction`.
2258 * @returns A promise to the result of the function.
2259 */
2260 $$eval<Selector extends string, Params extends unknown[], Func extends EvaluateFunc<[
2261 Array<NodeFor<Selector>>,
2262 ...Params
2263 ]> = EvaluateFunc<[Array<NodeFor<Selector>>, ...Params]>>(selector: Selector, pageFunction: Func | string, ...args: Params): Promise<Awaited<ReturnType<Func>>>;
2264 /**
2265 * @deprecated Use {@link Frame.$$} with the `xpath` prefix.
2266 *
2267 * Example: `await frame.$$('xpath/' + xpathExpression)`
2268 *
2269 * This method evaluates the given XPath expression and returns the results.
2270 * If `xpath` starts with `//` instead of `.//`, the dot will be appended
2271 * automatically.
2272 * @param expression - the XPath expression to evaluate.
2273 */
2274 $x(expression: string): Promise<Array<ElementHandle<Node>>>;
2275 /**
2276 * Waits for an element matching the given selector to appear in the frame.
2277 *
2278 * This method works across navigations.
2279 *
2280 * @example
2281 *
2282 * ```ts
2283 * import puppeteer from 'puppeteer';
2284 *
2285 * (async () => {
2286 * const browser = await puppeteer.launch();
2287 * const page = await browser.newPage();
2288 * let currentURL;
2289 * page
2290 * .mainFrame()
2291 * .waitForSelector('img')
2292 * .then(() => console.log('First URL with image: ' + currentURL));
2293 *
2294 * for (currentURL of [
2295 * 'https://example.com',
2296 * 'https://google.com',
2297 * 'https://bbc.com',
2298 * ]) {
2299 * await page.goto(currentURL);
2300 * }
2301 * await browser.close();
2302 * })();
2303 * ```
2304 *
2305 * @param selector - The selector to query and wait for.
2306 * @param options - Options for customizing waiting behavior.
2307 * @returns An element matching the given selector.
2308 * @throws Throws if an element matching the given selector doesn't appear.
2309 */
2310 waitForSelector<Selector extends string>(selector: Selector, options?: WaitForSelectorOptions): Promise<ElementHandle<NodeFor<Selector>> | null>;
2311 /**
2312 * @deprecated Use {@link Frame.waitForSelector} with the `xpath` prefix.
2313 *
2314 * Example: `await frame.waitForSelector('xpath/' + xpathExpression)`
2315 *
2316 * The method evaluates the XPath expression relative to the Frame.
2317 * If `xpath` starts with `//` instead of `.//`, the dot will be appended
2318 * automatically.
2319 *
2320 * Wait for the `xpath` to appear in page. If at the moment of calling the
2321 * method the `xpath` already exists, the method will return immediately. If
2322 * the xpath doesn't appear after the `timeout` milliseconds of waiting, the
2323 * function will throw.
2324 *
2325 * For a code example, see the example for {@link Frame.waitForSelector}. That
2326 * function behaves identically other than taking a CSS selector rather than
2327 * an XPath.
2328 *
2329 * @param xpath - the XPath expression to wait for.
2330 * @param options - options to configure the visibility of the element and how
2331 * long to wait before timing out.
2332 */
2333 waitForXPath(xpath: string, options?: WaitForSelectorOptions): Promise<ElementHandle<Node> | null>;
2334 /**
2335 * @example
2336 * The `waitForFunction` can be used to observe viewport size change:
2337 *
2338 * ```ts
2339 * import puppeteer from 'puppeteer';
2340 *
2341 * (async () => {
2342 * . const browser = await puppeteer.launch();
2343 * . const page = await browser.newPage();
2344 * . const watchDog = page.mainFrame().waitForFunction('window.innerWidth < 100');
2345 * . page.setViewport({width: 50, height: 50});
2346 * . await watchDog;
2347 * . await browser.close();
2348 * })();
2349 * ```
2350 *
2351 * To pass arguments from Node.js to the predicate of `page.waitForFunction` function:
2352 *
2353 * ```ts
2354 * const selector = '.foo';
2355 * await frame.waitForFunction(
2356 * selector => !!document.querySelector(selector),
2357 * {}, // empty options object
2358 * selector
2359 * );
2360 * ```
2361 *
2362 * @param pageFunction - the function to evaluate in the frame context.
2363 * @param options - options to configure the polling method and timeout.
2364 * @param args - arguments to pass to the `pageFunction`.
2365 * @returns the promise which resolve when the `pageFunction` returns a truthy value.
2366 */
2367 waitForFunction<Params extends unknown[], Func extends EvaluateFunc<Params> = EvaluateFunc<Params>>(pageFunction: Func | string, options?: FrameWaitForFunctionOptions, ...args: Params): Promise<HandleFor<Awaited<ReturnType<Func>>>>;
2368 /**
2369 * @returns The full HTML contents of the frame, including the DOCTYPE.
2370 */
2371 content(): Promise<string>;
2372 /**
2373 * Set the content of the frame.
2374 *
2375 * @param html - HTML markup to assign to the page.
2376 * @param options - Options to configure how long before timing out and at
2377 * what point to consider the content setting successful.
2378 */
2379 setContent(html: string, options?: {
2380 timeout?: number;
2381 waitUntil?: PuppeteerLifeCycleEvent | PuppeteerLifeCycleEvent[];
2382 }): Promise<void>;
2383 /**
2384 * @returns The frame's `name` attribute as specified in the tag.
2385 *
2386 * @remarks
2387 * If the name is empty, it returns the `id` attribute instead.
2388 *
2389 * @remarks
2390 * This value is calculated once when the frame is created, and will not
2391 * update if the attribute is changed later.
2392 */
2393 name(): string;
2394 /**
2395 * @returns The frame's URL.
2396 */
2397 url(): string;
2398 /**
2399 * @returns The parent frame, if any. Detached and main frames return `null`.
2400 */
2401 parentFrame(): Frame | null;
2402 /**
2403 * @returns An array of child frames.
2404 */
2405 childFrames(): Frame[];
2406 /**
2407 * @returns `true` if the frame has been detached. Otherwise, `false`.
2408 */
2409 isDetached(): boolean;
2410 /**
2411 * Adds a `<script>` tag into the page with the desired url or content.
2412 *
2413 * @param options - Options for the script.
2414 * @returns An {@link ElementHandle | element handle} to the injected
2415 * `<script>` element.
2416 */
2417 addScriptTag(options: FrameAddScriptTagOptions): Promise<ElementHandle<HTMLScriptElement>>;
2418 /**
2419 * Adds a `<link rel="stylesheet">` tag into the page with the desired URL or
2420 * a `<style type="text/css">` tag with the content.
2421 *
2422 * @returns An {@link ElementHandle | element handle} to the loaded `<link>`
2423 * or `<style>` element.
2424 */
2425 addStyleTag(options: Omit<FrameAddStyleTagOptions, 'url'>): Promise<ElementHandle<HTMLStyleElement>>;
2426 addStyleTag(options: FrameAddStyleTagOptions): Promise<ElementHandle<HTMLLinkElement>>;
2427 /**
2428 * Clicks the first element found that matches `selector`.
2429 *
2430 * @remarks
2431 * If `click()` triggers a navigation event and there's a separate
2432 * `page.waitForNavigation()` promise to be resolved, you may end up with a
2433 * race condition that yields unexpected results. The correct pattern for
2434 * click and wait for navigation is the following:
2435 *
2436 * ```ts
2437 * const [response] = await Promise.all([
2438 * page.waitForNavigation(waitOptions),
2439 * frame.click(selector, clickOptions),
2440 * ]);
2441 * ```
2442 *
2443 * @param selector - The selector to query for.
2444 */
2445 click(selector: string, options?: {
2446 delay?: number;
2447 button?: MouseButton;
2448 clickCount?: number;
2449 }): Promise<void>;
2450 /**
2451 * Focuses the first element that matches the `selector`.
2452 *
2453 * @param selector - The selector to query for.
2454 * @throws Throws if there's no element matching `selector`.
2455 */
2456 focus(selector: string): Promise<void>;
2457 /**
2458 * Hovers the pointer over the center of the first element that matches the
2459 * `selector`.
2460 *
2461 * @param selector - The selector to query for.
2462 * @throws Throws if there's no element matching `selector`.
2463 */
2464 hover(selector: string): Promise<void>;
2465 /**
2466 * Selects a set of value on the first `<select>` element that matches the
2467 * `selector`.
2468 *
2469 * @example
2470 *
2471 * ```ts
2472 * frame.select('select#colors', 'blue'); // single selection
2473 * frame.select('select#colors', 'red', 'green', 'blue'); // multiple selections
2474 * ```
2475 *
2476 * @param selector - The selector to query for.
2477 * @param values - The array of values to select. If the `<select>` has the
2478 * `multiple` attribute, all values are considered, otherwise only the first
2479 * one is taken into account.
2480 * @returns the list of values that were successfully selected.
2481 * @throws Throws if there's no `<select>` matching `selector`.
2482 */
2483 select(selector: string, ...values: string[]): Promise<string[]>;
2484 /**
2485 * Taps the first element that matches the `selector`.
2486 *
2487 * @param selector - The selector to query for.
2488 * @throws Throws if there's no element matching `selector`.
2489 */
2490 tap(selector: string): Promise<void>;
2491 /**
2492 * Sends a `keydown`, `keypress`/`input`, and `keyup` event for each character
2493 * in the text.
2494 *
2495 * @remarks
2496 * To press a special key, like `Control` or `ArrowDown`, use
2497 * {@link Keyboard.press}.
2498 *
2499 * @example
2500 *
2501 * ```ts
2502 * await frame.type('#mytextarea', 'Hello'); // Types instantly
2503 * await frame.type('#mytextarea', 'World', {delay: 100}); // Types slower, like a user
2504 * ```
2505 *
2506 * @param selector - the selector for the element to type into. If there are
2507 * multiple the first will be used.
2508 * @param text - text to type into the element
2509 * @param options - takes one option, `delay`, which sets the time to wait
2510 * between key presses in milliseconds. Defaults to `0`.
2511 */
2512 type(selector: string, text: string, options?: {
2513 delay: number;
2514 }): Promise<void>;
2515 /**
2516 * @deprecated Replace with `new Promise(r => setTimeout(r, milliseconds));`.
2517 *
2518 * Causes your script to wait for the given number of milliseconds.
2519 *
2520 * @remarks
2521 * It's generally recommended to not wait for a number of seconds, but instead
2522 * use {@link Frame.waitForSelector}, {@link Frame.waitForXPath} or
2523 * {@link Frame.waitForFunction} to wait for exactly the conditions you want.
2524 *
2525 * @example
2526 *
2527 * Wait for 1 second:
2528 *
2529 * ```ts
2530 * await frame.waitForTimeout(1000);
2531 * ```
2532 *
2533 * @param milliseconds - the number of milliseconds to wait.
2534 */
2535 waitForTimeout(milliseconds: number): Promise<void>;
2536 /**
2537 * @returns the frame's title.
2538 */
2539 title(): Promise<string>;
2540 /* Excluded from this release type: _navigated */
2541 /* Excluded from this release type: _navigatedWithinDocument */
2542 /* Excluded from this release type: _onLifecycleEvent */
2543 /* Excluded from this release type: _onLoadingStopped */
2544 /* Excluded from this release type: _onLoadingStarted */
2545 /* Excluded from this release type: _detach */
2546}
2547
2548/**
2549 * @public
2550 */
2551export declare interface FrameAddScriptTagOptions {
2552 /**
2553 * URL of the script to be added.
2554 */
2555 url?: string;
2556 /**
2557 * Path to a JavaScript file to be injected into the frame.
2558 *
2559 * @remarks
2560 * If `path` is a relative path, it is resolved relative to the current
2561 * working directory (`process.cwd()` in Node.js).
2562 */
2563 path?: string;
2564 /**
2565 * JavaScript to be injected into the frame.
2566 */
2567 content?: string;
2568 /**
2569 * Sets the `type` of the script. Use `module` in order to load an ES2015 module.
2570 */
2571 type?: string;
2572 /**
2573 * Sets the `id` of the script.
2574 */
2575 id?: string;
2576}
2577
2578/**
2579 * @public
2580 */
2581export declare interface FrameAddStyleTagOptions {
2582 /**
2583 * the URL of the CSS file to be added.
2584 */
2585 url?: string;
2586 /**
2587 * The path to a CSS file to be injected into the frame.
2588 * @remarks
2589 * If `path` is a relative path, it is resolved relative to the current
2590 * working directory (`process.cwd()` in Node.js).
2591 */
2592 path?: string;
2593 /**
2594 * Raw CSS content to be injected into the frame.
2595 */
2596 content?: string;
2597}
2598
2599/* Excluded from this release type: FrameManager */
2600
2601declare interface FrameManager_2 {
2602 frame(frameId: string): Frame | null;
2603}
2604
2605/* Excluded from this release type: FrameManagerEmittedEvents */
2606
2607/* Excluded from this release type: FrameTree */
2608
2609/**
2610 * @public
2611 */
2612export declare interface FrameWaitForFunctionOptions {
2613 /**
2614 * An interval at which the `pageFunction` is executed, defaults to `raf`. If
2615 * `polling` is a number, then it is treated as an interval in milliseconds at
2616 * which the function would be executed. If `polling` is a string, then it can
2617 * be one of the following values:
2618 *
2619 * - `raf` - to constantly execute `pageFunction` in `requestAnimationFrame`
2620 * callback. This is the tightest polling mode which is suitable to observe
2621 * styling changes.
2622 *
2623 * - `mutation` - to execute `pageFunction` on every DOM mutation.
2624 */
2625 polling?: 'raf' | 'mutation' | number;
2626 /**
2627 * Maximum time to wait in milliseconds. Defaults to `30000` (30 seconds).
2628 * Pass `0` to disable the timeout. Puppeteer's default timeout can be changed
2629 * using {@link Page.setDefaultTimeout}.
2630 */
2631 timeout?: number;
2632}
2633
2634/**
2635 * @public
2636 */
2637export declare interface GeolocationOptions {
2638 /**
2639 * Latitude between `-90` and `90`.
2640 */
2641 longitude: number;
2642 /**
2643 * Longitude between `-180` and `180`.
2644 */
2645 latitude: number;
2646 /**
2647 * Optional non-negative accuracy value.
2648 */
2649 accuracy?: number;
2650}
2651
2652/* Excluded from this release type: getCapturedLogs */
2653
2654/* Excluded from this release type: getExceptionMessage */
2655
2656/* Excluded from this release type: getFetch */
2657
2658/* Excluded from this release type: getQueryHandlerAndSelector */
2659
2660/* Excluded from this release type: getReadableAsBuffer */
2661
2662/* Excluded from this release type: getReadableFromProtocolStream */
2663
2664/**
2665 * @public
2666 */
2667export declare type HandleFor<T> = T extends Node ? ElementHandle<T> : JSHandle<T>;
2668
2669/**
2670 * @public
2671 */
2672export declare type HandleOr<T> = HandleFor<T> | JSHandle<T> | T;
2673
2674/**
2675 * @public
2676 */
2677export declare type Handler<T = unknown> = (event: T) => void;
2678
2679/**
2680 * Represents an HTTP request sent by a page.
2681 * @remarks
2682 *
2683 * Whenever the page sends a request, such as for a network resource, the
2684 * following events are emitted by Puppeteer's `page`:
2685 *
2686 * - `request`: emitted when the request is issued by the page.
2687 * - `requestfinished` - emitted when the response body is downloaded and the
2688 * request is complete.
2689 *
2690 * If request fails at some point, then instead of `requestfinished` event the
2691 * `requestfailed` event is emitted.
2692 *
2693 * All of these events provide an instance of `HTTPRequest` representing the
2694 * request that occurred:
2695 *
2696 * ```
2697 * page.on('request', request => ...)
2698 * ```
2699 *
2700 * NOTE: HTTP Error responses, such as 404 or 503, are still successful
2701 * responses from HTTP standpoint, so request will complete with
2702 * `requestfinished` event.
2703 *
2704 * If request gets a 'redirect' response, the request is successfully finished
2705 * with the `requestfinished` event, and a new request is issued to a
2706 * redirected url.
2707 *
2708 * @public
2709 */
2710export declare class HTTPRequest {
2711 #private;
2712 /* Excluded from this release type: _requestId */
2713 /* Excluded from this release type: _interceptionId */
2714 /* Excluded from this release type: _failureText */
2715 /* Excluded from this release type: _response */
2716 /* Excluded from this release type: _fromMemoryCache */
2717 /* Excluded from this release type: _redirectChain */
2718 /**
2719 * Warning! Using this client can break Puppeteer. Use with caution.
2720 *
2721 * @experimental
2722 */
2723 get client(): CDPSession_3;
2724 /* Excluded from this release type: __constructor */
2725 /**
2726 * @returns the URL of the request
2727 */
2728 url(): string;
2729 /**
2730 * @returns the `ContinueRequestOverrides` that will be used
2731 * if the interception is allowed to continue (ie, `abort()` and
2732 * `respond()` aren't called).
2733 */
2734 continueRequestOverrides(): ContinueRequestOverrides;
2735 /**
2736 * @returns The `ResponseForRequest` that gets used if the
2737 * interception is allowed to respond (ie, `abort()` is not called).
2738 */
2739 responseForRequest(): Partial<ResponseForRequest> | null;
2740 /**
2741 * @returns the most recent reason for aborting the request
2742 */
2743 abortErrorReason(): Protocol.Network.ErrorReason | null;
2744 /**
2745 * @returns An InterceptResolutionState object describing the current resolution
2746 * action and priority.
2747 *
2748 * InterceptResolutionState contains:
2749 * action: InterceptResolutionAction
2750 * priority?: number
2751 *
2752 * InterceptResolutionAction is one of: `abort`, `respond`, `continue`,
2753 * `disabled`, `none`, or `already-handled`.
2754 */
2755 interceptResolutionState(): InterceptResolutionState;
2756 /**
2757 * @returns `true` if the intercept resolution has already been handled,
2758 * `false` otherwise.
2759 */
2760 isInterceptResolutionHandled(): boolean;
2761 /**
2762 * Adds an async request handler to the processing queue.
2763 * Deferred handlers are not guaranteed to execute in any particular order,
2764 * but they are guaranteed to resolve before the request interception
2765 * is finalized.
2766 */
2767 enqueueInterceptAction(pendingHandler: () => void | PromiseLike<unknown>): void;
2768 /**
2769 * Awaits pending interception handlers and then decides how to fulfill
2770 * the request interception.
2771 */
2772 finalizeInterceptions(): Promise<void>;
2773 /**
2774 * Contains the request's resource type as it was perceived by the rendering
2775 * engine.
2776 */
2777 resourceType(): ResourceType;
2778 /**
2779 * @returns the method used (`GET`, `POST`, etc.)
2780 */
2781 method(): string;
2782 /**
2783 * @returns the request's post body, if any.
2784 */
2785 postData(): string | undefined;
2786 /**
2787 * @returns an object with HTTP headers associated with the request. All
2788 * header names are lower-case.
2789 */
2790 headers(): Record<string, string>;
2791 /**
2792 * @returns A matching `HTTPResponse` object, or null if the response has not
2793 * been received yet.
2794 */
2795 response(): HTTPResponse | null;
2796 /**
2797 * @returns the frame that initiated the request, or null if navigating to
2798 * error pages.
2799 */
2800 frame(): Frame | null;
2801 /**
2802 * @returns true if the request is the driver of the current frame's navigation.
2803 */
2804 isNavigationRequest(): boolean;
2805 /**
2806 * @returns the initiator of the request.
2807 */
2808 initiator(): Protocol.Network.Initiator;
2809 /**
2810 * A `redirectChain` is a chain of requests initiated to fetch a resource.
2811 * @remarks
2812 *
2813 * `redirectChain` is shared between all the requests of the same chain.
2814 *
2815 * For example, if the website `http://example.com` has a single redirect to
2816 * `https://example.com`, then the chain will contain one request:
2817 *
2818 * ```ts
2819 * const response = await page.goto('http://example.com');
2820 * const chain = response.request().redirectChain();
2821 * console.log(chain.length); // 1
2822 * console.log(chain[0].url()); // 'http://example.com'
2823 * ```
2824 *
2825 * If the website `https://google.com` has no redirects, then the chain will be empty:
2826 *
2827 * ```ts
2828 * const response = await page.goto('https://google.com');
2829 * const chain = response.request().redirectChain();
2830 * console.log(chain.length); // 0
2831 * ```
2832 *
2833 * @returns the chain of requests - if a server responds with at least a
2834 * single redirect, this chain will contain all requests that were redirected.
2835 */
2836 redirectChain(): HTTPRequest[];
2837 /**
2838 * Access information about the request's failure.
2839 *
2840 * @remarks
2841 *
2842 * @example
2843 *
2844 * Example of logging all failed requests:
2845 *
2846 * ```ts
2847 * page.on('requestfailed', request => {
2848 * console.log(request.url() + ' ' + request.failure().errorText);
2849 * });
2850 * ```
2851 *
2852 * @returns `null` unless the request failed. If the request fails this can
2853 * return an object with `errorText` containing a human-readable error
2854 * message, e.g. `net::ERR_FAILED`. It is not guaranteed that there will be
2855 * failure text if the request fails.
2856 */
2857 failure(): {
2858 errorText: string;
2859 } | null;
2860 /**
2861 * Continues request with optional request overrides.
2862 *
2863 * @remarks
2864 *
2865 * To use this, request
2866 * interception should be enabled with {@link Page.setRequestInterception}.
2867 *
2868 * Exception is immediately thrown if the request interception is not enabled.
2869 *
2870 * @example
2871 *
2872 * ```ts
2873 * await page.setRequestInterception(true);
2874 * page.on('request', request => {
2875 * // Override headers
2876 * const headers = Object.assign({}, request.headers(), {
2877 * foo: 'bar', // set "foo" header
2878 * origin: undefined, // remove "origin" header
2879 * });
2880 * request.continue({headers});
2881 * });
2882 * ```
2883 *
2884 * @param overrides - optional overrides to apply to the request.
2885 * @param priority - If provided, intercept is resolved using
2886 * cooperative handling rules. Otherwise, intercept is resolved
2887 * immediately.
2888 */
2889 continue(overrides?: ContinueRequestOverrides, priority?: number): Promise<void>;
2890 /**
2891 * Fulfills a request with the given response.
2892 *
2893 * @remarks
2894 *
2895 * To use this, request
2896 * interception should be enabled with {@link Page.setRequestInterception}.
2897 *
2898 * Exception is immediately thrown if the request interception is not enabled.
2899 *
2900 * @example
2901 * An example of fulfilling all requests with 404 responses:
2902 *
2903 * ```ts
2904 * await page.setRequestInterception(true);
2905 * page.on('request', request => {
2906 * request.respond({
2907 * status: 404,
2908 * contentType: 'text/plain',
2909 * body: 'Not Found!',
2910 * });
2911 * });
2912 * ```
2913 *
2914 * NOTE: Mocking responses for dataURL requests is not supported.
2915 * Calling `request.respond` for a dataURL request is a noop.
2916 *
2917 * @param response - the response to fulfill the request with.
2918 * @param priority - If provided, intercept is resolved using
2919 * cooperative handling rules. Otherwise, intercept is resolved
2920 * immediately.
2921 */
2922 respond(response: Partial<ResponseForRequest>, priority?: number): Promise<void>;
2923 /**
2924 * Aborts a request.
2925 *
2926 * @remarks
2927 * To use this, request interception should be enabled with
2928 * {@link Page.setRequestInterception}. If it is not enabled, this method will
2929 * throw an exception immediately.
2930 *
2931 * @param errorCode - optional error code to provide.
2932 * @param priority - If provided, intercept is resolved using
2933 * cooperative handling rules. Otherwise, intercept is resolved
2934 * immediately.
2935 */
2936 abort(errorCode?: ErrorCode, priority?: number): Promise<void>;
2937}
2938
2939/**
2940 * The HTTPResponse class represents responses which are received by the
2941 * {@link Page} class.
2942 *
2943 * @public
2944 */
2945export declare class HTTPResponse {
2946 #private;
2947 /* Excluded from this release type: __constructor */
2948 /* Excluded from this release type: _resolveBody */
2949 /**
2950 * @returns The IP address and port number used to connect to the remote
2951 * server.
2952 */
2953 remoteAddress(): RemoteAddress;
2954 /**
2955 * @returns The URL of the response.
2956 */
2957 url(): string;
2958 /**
2959 * @returns True if the response was successful (status in the range 200-299).
2960 */
2961 ok(): boolean;
2962 /**
2963 * @returns The status code of the response (e.g., 200 for a success).
2964 */
2965 status(): number;
2966 /**
2967 * @returns The status text of the response (e.g. usually an "OK" for a
2968 * success).
2969 */
2970 statusText(): string;
2971 /**
2972 * @returns An object with HTTP headers associated with the response. All
2973 * header names are lower-case.
2974 */
2975 headers(): Record<string, string>;
2976 /**
2977 * @returns {@link SecurityDetails} if the response was received over the
2978 * secure connection, or `null` otherwise.
2979 */
2980 securityDetails(): SecurityDetails | null;
2981 /**
2982 * @returns Timing information related to the response.
2983 */
2984 timing(): Protocol.Network.ResourceTiming | null;
2985 /**
2986 * @returns Promise which resolves to a buffer with response body.
2987 */
2988 buffer(): Promise<Buffer>;
2989 /**
2990 * @returns Promise which resolves to a text representation of response body.
2991 */
2992 text(): Promise<string>;
2993 /**
2994 *
2995 * @returns Promise which resolves to a JSON representation of response body.
2996 *
2997 * @remarks
2998 *
2999 * This method will throw if the response body is not parsable via
3000 * `JSON.parse`.
3001 */
3002 json(): Promise<any>;
3003 /**
3004 * @returns A matching {@link HTTPRequest} object.
3005 */
3006 request(): HTTPRequest;
3007 /**
3008 * @returns True if the response was served from either the browser's disk
3009 * cache or memory cache.
3010 */
3011 fromCache(): boolean;
3012 /**
3013 * @returns True if the response was served by a service worker.
3014 */
3015 fromServiceWorker(): boolean;
3016 /**
3017 * @returns A {@link Frame} that initiated this response, or `null` if
3018 * navigating to error pages.
3019 */
3020 frame(): Frame | null;
3021 }
3022
3023 /* Excluded from this release type: importDebug */
3024
3025 /* Excluded from this release type: importFS */
3026
3027 /* Excluded from this release type: InnerLazyParams */
3028
3029 /**
3030 * @public
3031 */
3032 export declare type InnerParams<T extends unknown[]> = {
3033 [K in keyof T]: FlattenHandle<T[K]>;
3034 };
3035
3036 /**
3037 * @public
3038 */
3039 export declare enum InterceptResolutionAction {
3040 Abort = "abort",
3041 Respond = "respond",
3042 Continue = "continue",
3043 Disabled = "disabled",
3044 None = "none",
3045 AlreadyHandled = "already-handled"
3046 }
3047
3048 /**
3049 * @public
3050 */
3051 export declare interface InterceptResolutionState {
3052 action: InterceptResolutionAction;
3053 priority?: number;
3054 }
3055
3056 /**
3057 * @public
3058 *
3059 * @deprecated please use {@link InterceptResolutionAction} instead.
3060 */
3061 export declare type InterceptResolutionStrategy = InterceptResolutionAction;
3062
3063 /**
3064 * @public
3065 */
3066 export declare interface InternalNetworkConditions extends NetworkConditions {
3067 offline: boolean;
3068 }
3069
3070 /* Excluded from this release type: InternalQueryHandler */
3071
3072 /* Excluded from this release type: IntervalPoller */
3073
3074 /* Excluded from this release type: isErrnoException */
3075
3076 /* Excluded from this release type: isErrorLike */
3077
3078 /* Excluded from this release type: isNumber */
3079
3080 /* Excluded from this release type: IsolatedWorld */
3081
3082 /* Excluded from this release type: IsolatedWorldChart */
3083
3084 /* Excluded from this release type: IsPageTargetCallback */
3085
3086 /* Excluded from this release type: isString */
3087
3088 /* Excluded from this release type: isTargetClosedError */
3089
3090 /**
3091 * @public
3092 */
3093 export declare class JSCoverage {
3094 #private;
3095 constructor(client: CDPSession);
3096 start(options?: {
3097 resetOnNavigation?: boolean;
3098 reportAnonymousScripts?: boolean;
3099 includeRawScriptCoverage?: boolean;
3100 useBlockCoverage?: boolean;
3101 }): Promise<void>;
3102 stop(): Promise<JSCoverageEntry[]>;
3103 }
3104
3105 /**
3106 * The CoverageEntry class for JavaScript
3107 * @public
3108 */
3109 export declare interface JSCoverageEntry extends CoverageEntry {
3110 /**
3111 * Raw V8 script coverage entry.
3112 */
3113 rawScriptCoverage?: Protocol.Profiler.ScriptCoverage;
3114 }
3115
3116 /**
3117 * Set of configurable options for JS coverage.
3118 * @public
3119 */
3120 export declare interface JSCoverageOptions {
3121 /**
3122 * Whether to reset coverage on every navigation.
3123 */
3124 resetOnNavigation?: boolean;
3125 /**
3126 * Whether anonymous scripts generated by the page should be reported.
3127 */
3128 reportAnonymousScripts?: boolean;
3129 /**
3130 * Whether the result includes raw V8 script coverage entries.
3131 */
3132 includeRawScriptCoverage?: boolean;
3133 /**
3134 * Whether to collect coverage information at the block level.
3135 * If true, coverage will be collected at the block level (this is the default).
3136 * If false, coverage will be collected at the function level.
3137 */
3138 useBlockCoverage?: boolean;
3139 }
3140
3141 /**
3142 * Represents a reference to a JavaScript object. Instances can be created using
3143 * {@link Page.evaluateHandle}.
3144 *
3145 * Handles prevent the referenced JavaScript object from being garbage-collected
3146 * unless the handle is purposely {@link JSHandle.dispose | disposed}. JSHandles
3147 * are auto-disposed when their associated frame is navigated away or the parent
3148 * context gets destroyed.
3149 *
3150 * Handles can be used as arguments for any evaluation function such as
3151 * {@link Page.$eval}, {@link Page.evaluate}, and {@link Page.evaluateHandle}.
3152 * They are resolved to their referenced object.
3153 *
3154 * @example
3155 *
3156 * ```ts
3157 * const windowHandle = await page.evaluateHandle(() => window);
3158 * ```
3159 *
3160 * @public
3161 */
3162 export declare class JSHandle<T = unknown> {
3163 #private;
3164 /**
3165 * Used for nominally typing {@link JSHandle}.
3166 */
3167 [__JSHandleSymbol]?: T;
3168 /* Excluded from this release type: client */
3169 /* Excluded from this release type: disposed */
3170 /* Excluded from this release type: __constructor */
3171 /* Excluded from this release type: executionContext */
3172 /**
3173 * Evaluates the given function with the current handle as its first argument.
3174 *
3175 * @see {@link ExecutionContext.evaluate} for more details.
3176 */
3177 evaluate<Params extends unknown[], Func extends EvaluateFunc<[this, ...Params]> = EvaluateFunc<[
3178 this,
3179 ...Params
3180 ]>>(pageFunction: Func | string, ...args: Params): Promise<Awaited<ReturnType<Func>>>;
3181 /**
3182 * Evaluates the given function with the current handle as its first argument.
3183 *
3184 * @see {@link ExecutionContext.evaluateHandle} for more details.
3185 */
3186 evaluateHandle<Params extends unknown[], Func extends EvaluateFunc<[this, ...Params]> = EvaluateFunc<[
3187 this,
3188 ...Params
3189 ]>>(pageFunction: Func | string, ...args: Params): Promise<HandleFor<Awaited<ReturnType<Func>>>>;
3190 /**
3191 * Fetches a single property from the referenced object.
3192 */
3193 getProperty<K extends keyof T>(propertyName: HandleOr<K>): Promise<HandleFor<T[K]>>;
3194 getProperty(propertyName: string): Promise<JSHandle<unknown>>;
3195 /**
3196 * Gets a map of handles representing the properties of the current handle.
3197 *
3198 * @example
3199 *
3200 * ```ts
3201 * const listHandle = await page.evaluateHandle(() => document.body.children);
3202 * const properties = await listHandle.getProperties();
3203 * const children = [];
3204 * for (const property of properties.values()) {
3205 * const element = property.asElement();
3206 * if (element) {
3207 * children.push(element);
3208 * }
3209 * }
3210 * children; // holds elementHandles to all children of document.body
3211 * ```
3212 */
3213 getProperties(): Promise<Map<string, JSHandle>>;
3214 /**
3215 * @returns A vanilla object representing the serializable portions of the
3216 * referenced object.
3217 * @throws Throws if the object cannot be serialized due to circularity.
3218 *
3219 * @remarks
3220 * If the object has a `toJSON` function, it **will not** be called.
3221 */
3222 jsonValue(): Promise<T>;
3223 /**
3224 * @returns Either `null` or the handle itself if the handle is an
3225 * instance of {@link ElementHandle}.
3226 */
3227 asElement(): ElementHandle<Node> | null;
3228 /**
3229 * Releases the object referenced by the handle for garbage collection.
3230 */
3231 dispose(): Promise<void>;
3232 /**
3233 * Returns a string representation of the JSHandle.
3234 *
3235 * @remarks
3236 * Useful during debugging.
3237 */
3238 toString(): string;
3239 /**
3240 * Provides access to the
3241 * [Protocol.Runtime.RemoteObject](https://chromedevtools.github.io/devtools-protocol/tot/Runtime/#type-RemoteObject)
3242 * backing this handle.
3243 */
3244 remoteObject(): Protocol.Runtime.RemoteObject;
3245 }
3246
3247 /**
3248 * Keyboard provides an api for managing a virtual keyboard.
3249 * The high level api is {@link Keyboard."type"},
3250 * which takes raw characters and generates proper keydown, keypress/input,
3251 * and keyup events on your page.
3252 *
3253 * @remarks
3254 * For finer control, you can use {@link Keyboard.down},
3255 * {@link Keyboard.up}, and {@link Keyboard.sendCharacter}
3256 * to manually fire events as if they were generated from a real keyboard.
3257 *
3258 * On macOS, keyboard shortcuts like `⌘ A` -\> Select All do not work.
3259 * See {@link https://github.com/puppeteer/puppeteer/issues/1313 | #1313}.
3260 *
3261 * @example
3262 * An example of holding down `Shift` in order to select and delete some text:
3263 *
3264 * ```ts
3265 * await page.keyboard.type('Hello World!');
3266 * await page.keyboard.press('ArrowLeft');
3267 *
3268 * await page.keyboard.down('Shift');
3269 * for (let i = 0; i < ' World'.length; i++)
3270 * await page.keyboard.press('ArrowLeft');
3271 * await page.keyboard.up('Shift');
3272 *
3273 * await page.keyboard.press('Backspace');
3274 * // Result text will end up saying 'Hello!'
3275 * ```
3276 *
3277 * @example
3278 * An example of pressing `A`
3279 *
3280 * ```ts
3281 * await page.keyboard.down('Shift');
3282 * await page.keyboard.press('KeyA');
3283 * await page.keyboard.up('Shift');
3284 * ```
3285 *
3286 * @public
3287 */
3288 export declare class Keyboard {
3289 #private;
3290 /* Excluded from this release type: _modifiers */
3291 /* Excluded from this release type: __constructor */
3292 /**
3293 * Dispatches a `keydown` event.
3294 *
3295 * @remarks
3296 * If `key` is a single character and no modifier keys besides `Shift`
3297 * are being held down, a `keypress`/`input` event will also generated.
3298 * The `text` option can be specified to force an input event to be generated.
3299 * If `key` is a modifier key, `Shift`, `Meta`, `Control`, or `Alt`,
3300 * subsequent key presses will be sent with that modifier active.
3301 * To release the modifier key, use {@link Keyboard.up}.
3302 *
3303 * After the key is pressed once, subsequent calls to
3304 * {@link Keyboard.down} will have
3305 * {@link https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/repeat | repeat}
3306 * set to true. To release the key, use {@link Keyboard.up}.
3307 *
3308 * Modifier keys DO influence {@link Keyboard.down}.
3309 * Holding down `Shift` will type the text in upper case.
3310 *
3311 * @param key - Name of key to press, such as `ArrowLeft`.
3312 * See {@link KeyInput} for a list of all key names.
3313 *
3314 * @param options - An object of options. Accepts text which, if specified,
3315 * generates an input event with this text. Accepts commands which, if specified,
3316 * is the commands of keyboard shortcuts,
3317 * see {@link https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/core/editing/commands/editor_command_names.h | Chromium Source Code} for valid command names.
3318 */
3319 down(key: KeyInput, options?: {
3320 text?: string;
3321 commands?: string[];
3322 }): Promise<void>;
3323 /**
3324 * Dispatches a `keyup` event.
3325 *
3326 * @param key - Name of key to release, such as `ArrowLeft`.
3327 * See {@link KeyInput | KeyInput}
3328 * for a list of all key names.
3329 */
3330 up(key: KeyInput): Promise<void>;
3331 /**
3332 * Dispatches a `keypress` and `input` event.
3333 * This does not send a `keydown` or `keyup` event.
3334 *
3335 * @remarks
3336 * Modifier keys DO NOT effect {@link Keyboard.sendCharacter | Keyboard.sendCharacter}.
3337 * Holding down `Shift` will not type the text in upper case.
3338 *
3339 * @example
3340 *
3341 * ```ts
3342 * page.keyboard.sendCharacter('嗨');
3343 * ```
3344 *
3345 * @param char - Character to send into the page.
3346 */
3347 sendCharacter(char: string): Promise<void>;
3348 private charIsKey;
3349 /**
3350 * Sends a `keydown`, `keypress`/`input`,
3351 * and `keyup` event for each character in the text.
3352 *
3353 * @remarks
3354 * To press a special key, like `Control` or `ArrowDown`,
3355 * use {@link Keyboard.press}.
3356 *
3357 * Modifier keys DO NOT effect `keyboard.type`.
3358 * Holding down `Shift` will not type the text in upper case.
3359 *
3360 * @example
3361 *
3362 * ```ts
3363 * await page.keyboard.type('Hello'); // Types instantly
3364 * await page.keyboard.type('World', {delay: 100}); // Types slower, like a user
3365 * ```
3366 *
3367 * @param text - A text to type into a focused element.
3368 * @param options - An object of options. Accepts delay which,
3369 * if specified, is the time to wait between `keydown` and `keyup` in milliseconds.
3370 * Defaults to 0.
3371 */
3372 type(text: string, options?: {
3373 delay?: number;
3374 }): Promise<void>;
3375 /**
3376 * Shortcut for {@link Keyboard.down}
3377 * and {@link Keyboard.up}.
3378 *
3379 * @remarks
3380 * If `key` is a single character and no modifier keys besides `Shift`
3381 * are being held down, a `keypress`/`input` event will also generated.
3382 * The `text` option can be specified to force an input event to be generated.
3383 *
3384 * Modifier keys DO effect {@link Keyboard.press}.
3385 * Holding down `Shift` will type the text in upper case.
3386 *
3387 * @param key - Name of key to press, such as `ArrowLeft`.
3388 * See {@link KeyInput} for a list of all key names.
3389 *
3390 * @param options - An object of options. Accepts text which, if specified,
3391 * generates an input event with this text. Accepts delay which,
3392 * if specified, is the time to wait between `keydown` and `keyup` in milliseconds.
3393 * Defaults to 0. Accepts commands which, if specified,
3394 * is the commands of keyboard shortcuts,
3395 * see {@link https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/core/editing/commands/editor_command_names.h | Chromium Source Code} for valid command names.
3396 */
3397 press(key: KeyInput, options?: {
3398 delay?: number;
3399 text?: string;
3400 commands?: string[];
3401 }): Promise<void>;
3402 }
3403
3404 /* Excluded from this release type: KeyDefinition */
3405
3406 /* Excluded from this release type: _keyDefinitions */
3407
3408 /**
3409 * All the valid keys that can be passed to functions that take user input, such
3410 * as {@link Keyboard.press | keyboard.press }
3411 *
3412 * @public
3413 */
3414 export declare type KeyInput = '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' | 'Power' | 'Eject' | 'Abort' | 'Help' | 'Backspace' | 'Tab' | 'Numpad5' | 'NumpadEnter' | 'Enter' | '\r' | '\n' | 'ShiftLeft' | 'ShiftRight' | 'ControlLeft' | 'ControlRight' | 'AltLeft' | 'AltRight' | 'Pause' | 'CapsLock' | 'Escape' | 'Convert' | 'NonConvert' | 'Space' | 'Numpad9' | 'PageUp' | 'Numpad3' | 'PageDown' | 'End' | 'Numpad1' | 'Home' | 'Numpad7' | 'ArrowLeft' | 'Numpad4' | 'Numpad8' | 'ArrowUp' | 'ArrowRight' | 'Numpad6' | 'Numpad2' | 'ArrowDown' | 'Select' | 'Open' | 'PrintScreen' | 'Insert' | 'Numpad0' | 'Delete' | 'NumpadDecimal' | 'Digit0' | 'Digit1' | 'Digit2' | 'Digit3' | 'Digit4' | 'Digit5' | 'Digit6' | 'Digit7' | 'Digit8' | 'Digit9' | 'KeyA' | 'KeyB' | 'KeyC' | 'KeyD' | 'KeyE' | 'KeyF' | 'KeyG' | 'KeyH' | 'KeyI' | 'KeyJ' | 'KeyK' | 'KeyL' | 'KeyM' | 'KeyN' | 'KeyO' | 'KeyP' | 'KeyQ' | 'KeyR' | 'KeyS' | 'KeyT' | 'KeyU' | 'KeyV' | 'KeyW' | 'KeyX' | 'KeyY' | 'KeyZ' | 'MetaLeft' | 'MetaRight' | 'ContextMenu' | 'NumpadMultiply' | 'NumpadAdd' | 'NumpadSubtract' | 'NumpadDivide' | 'F1' | 'F2' | 'F3' | 'F4' | 'F5' | 'F6' | 'F7' | 'F8' | 'F9' | 'F10' | 'F11' | 'F12' | 'F13' | 'F14' | 'F15' | 'F16' | 'F17' | 'F18' | 'F19' | 'F20' | 'F21' | 'F22' | 'F23' | 'F24' | 'NumLock' | 'ScrollLock' | 'AudioVolumeMute' | 'AudioVolumeDown' | 'AudioVolumeUp' | 'MediaTrackNext' | 'MediaTrackPrevious' | 'MediaStop' | 'MediaPlayPause' | 'Semicolon' | 'Equal' | 'NumpadEqual' | 'Comma' | 'Minus' | 'Period' | 'Slash' | 'Backquote' | 'BracketLeft' | 'Backslash' | 'BracketRight' | 'Quote' | 'AltGraph' | 'Props' | 'Cancel' | 'Clear' | 'Shift' | 'Control' | 'Alt' | 'Accept' | 'ModeChange' | ' ' | 'Print' | 'Execute' | '\u0000' | 'a' | 'b' | 'c' | 'd' | 'e' | 'f' | 'g' | 'h' | 'i' | 'j' | 'k' | 'l' | 'm' | 'n' | 'o' | 'p' | 'q' | 'r' | 's' | 't' | 'u' | 'v' | 'w' | 'x' | 'y' | 'z' | 'Meta' | '*' | '+' | '-' | '/' | ';' | '=' | ',' | '.' | '`' | '[' | '\\' | ']' | "'" | 'Attn' | 'CrSel' | 'ExSel' | 'EraseEof' | 'Play' | 'ZoomOut' | ')' | '!' | '@' | '#' | '$' | '%' | '^' | '&' | '(' | 'A' | 'B' | 'C' | 'D' | 'E' | 'F' | 'G' | 'H' | 'I' | 'J' | 'K' | 'L' | 'M' | 'N' | 'O' | 'P' | 'Q' | 'R' | 'S' | 'T' | 'U' | 'V' | 'W' | 'X' | 'Y' | 'Z' | ':' | '<' | '_' | '>' | '?' | '~' | '{' | '|' | '}' | '"' | 'SoftLeft' | 'SoftRight' | 'Camera' | 'Call' | 'EndCall' | 'VolumeDown' | 'VolumeUp';
3415
3416 /**
3417 * A list of devices to be used with {@link Page.emulate}.
3418 *
3419 * @example
3420 *
3421 * ```ts
3422 * import {KnownDevices} from 'puppeteer';
3423 * const iPhone = KnownDevices['iPhone 6'];
3424 *
3425 * (async () => {
3426 * const browser = await puppeteer.launch();
3427 * const page = await browser.newPage();
3428 * await page.emulate(iPhone);
3429 * await page.goto('https://www.google.com');
3430 * // other actions...
3431 * await browser.close();
3432 * })();
3433 * ```
3434 *
3435 * @public
3436 */
3437 export declare const KnownDevices: Readonly<Record<"Blackberry PlayBook" | "Blackberry PlayBook landscape" | "BlackBerry Z30" | "BlackBerry Z30 landscape" | "Galaxy Note 3" | "Galaxy Note 3 landscape" | "Galaxy Note II" | "Galaxy Note II landscape" | "Galaxy S III" | "Galaxy S III landscape" | "Galaxy S5" | "Galaxy S5 landscape" | "Galaxy S8" | "Galaxy S8 landscape" | "Galaxy S9+" | "Galaxy S9+ landscape" | "Galaxy Tab S4" | "Galaxy Tab S4 landscape" | "iPad" | "iPad landscape" | "iPad (gen 6)" | "iPad (gen 6) landscape" | "iPad (gen 7)" | "iPad (gen 7) landscape" | "iPad Mini" | "iPad Mini landscape" | "iPad Pro" | "iPad Pro landscape" | "iPad Pro 11" | "iPad Pro 11 landscape" | "iPhone 4" | "iPhone 4 landscape" | "iPhone 5" | "iPhone 5 landscape" | "iPhone 6" | "iPhone 6 landscape" | "iPhone 6 Plus" | "iPhone 6 Plus landscape" | "iPhone 7" | "iPhone 7 landscape" | "iPhone 7 Plus" | "iPhone 7 Plus landscape" | "iPhone 8" | "iPhone 8 landscape" | "iPhone 8 Plus" | "iPhone 8 Plus landscape" | "iPhone SE" | "iPhone SE landscape" | "iPhone X" | "iPhone X landscape" | "iPhone XR" | "iPhone XR landscape" | "iPhone 11" | "iPhone 11 landscape" | "iPhone 11 Pro" | "iPhone 11 Pro landscape" | "iPhone 11 Pro Max" | "iPhone 11 Pro Max landscape" | "iPhone 12" | "iPhone 12 landscape" | "iPhone 12 Pro" | "iPhone 12 Pro landscape" | "iPhone 12 Pro Max" | "iPhone 12 Pro Max landscape" | "iPhone 12 Mini" | "iPhone 12 Mini landscape" | "iPhone 13" | "iPhone 13 landscape" | "iPhone 13 Pro" | "iPhone 13 Pro landscape" | "iPhone 13 Pro Max" | "iPhone 13 Pro Max landscape" | "iPhone 13 Mini" | "iPhone 13 Mini landscape" | "JioPhone 2" | "JioPhone 2 landscape" | "Kindle Fire HDX" | "Kindle Fire HDX landscape" | "LG Optimus L70" | "LG Optimus L70 landscape" | "Microsoft Lumia 550" | "Microsoft Lumia 950" | "Microsoft Lumia 950 landscape" | "Nexus 10" | "Nexus 10 landscape" | "Nexus 4" | "Nexus 4 landscape" | "Nexus 5" | "Nexus 5 landscape" | "Nexus 5X" | "Nexus 5X landscape" | "Nexus 6" | "Nexus 6 landscape" | "Nexus 6P" | "Nexus 6P landscape" | "Nexus 7" | "Nexus 7 landscape" | "Nokia Lumia 520" | "Nokia Lumia 520 landscape" | "Nokia N9" | "Nokia N9 landscape" | "Pixel 2" | "Pixel 2 landscape" | "Pixel 2 XL" | "Pixel 2 XL landscape" | "Pixel 3" | "Pixel 3 landscape" | "Pixel 4" | "Pixel 4 landscape" | "Pixel 4a (5G)" | "Pixel 4a (5G) landscape" | "Pixel 5" | "Pixel 5 landscape" | "Moto G4" | "Moto G4 landscape", Device>>;
3438
3439 declare type Last<Arr extends NonEmptyReadonlyArray<unknown>> = Arr extends [
3440 infer Head,
3441 ...infer Tail
3442 ] ? Tail extends NonEmptyReadonlyArray<unknown> ? Last<Tail> : Head : never;
3443
3444 export declare const launch: (options?: PuppeteerLaunchOptions | undefined) => Promise<Browser>;
3445
3446 /**
3447 * Generic launch options that can be passed when launching any browser.
3448 * @public
3449 */
3450 export declare interface LaunchOptions {
3451 /**
3452 * Chrome Release Channel
3453 */
3454 channel?: ChromeReleaseChannel;
3455 /**
3456 * Path to a browser executable to use instead of the bundled Chromium. Note
3457 * that Puppeteer is only guaranteed to work with the bundled Chromium, so use
3458 * this setting at your own risk.
3459 */
3460 executablePath?: string;
3461 /**
3462 * If `true`, do not use `puppeteer.defaultArgs()` when creating a browser. If
3463 * an array is provided, these args will be filtered out. Use this with care -
3464 * you probably want the default arguments Puppeteer uses.
3465 * @defaultValue false
3466 */
3467 ignoreDefaultArgs?: boolean | string[];
3468 /**
3469 * Close the browser process on `Ctrl+C`.
3470 * @defaultValue `true`
3471 */
3472 handleSIGINT?: boolean;
3473 /**
3474 * Close the browser process on `SIGTERM`.
3475 * @defaultValue `true`
3476 */
3477 handleSIGTERM?: boolean;
3478 /**
3479 * Close the browser process on `SIGHUP`.
3480 * @defaultValue `true`
3481 */
3482 handleSIGHUP?: boolean;
3483 /**
3484 * Maximum time in milliseconds to wait for the browser to start.
3485 * Pass `0` to disable the timeout.
3486 * @defaultValue 30000 (30 seconds).
3487 */
3488 timeout?: number;
3489 /**
3490 * If true, pipes the browser process stdout and stderr to `process.stdout`
3491 * and `process.stderr`.
3492 * @defaultValue false
3493 */
3494 dumpio?: boolean;
3495 /**
3496 * Specify environment variables that will be visible to the browser.
3497 * @defaultValue The contents of `process.env`.
3498 */
3499 env?: Record<string, string | undefined>;
3500 /**
3501 * Connect to a browser over a pipe instead of a WebSocket.
3502 * @defaultValue false
3503 */
3504 pipe?: boolean;
3505 /**
3506 * Which browser to launch.
3507 * @defaultValue `chrome`
3508 */
3509 product?: Product;
3510 /**
3511 * {@link https://searchfox.org/mozilla-release/source/modules/libpref/init/all.js | Additional preferences } that can be passed when launching with Firefox.
3512 */
3513 extraPrefsFirefox?: Record<string, unknown>;
3514 /**
3515 * Whether to wait for the initial page to be ready.
3516 * Useful when a user explicitly disables that (e.g. `--no-startup-window` for Chrome).
3517 * @defaultValue true
3518 */
3519 waitForInitialPage?: boolean;
3520 }
3521
3522 /* Excluded from this release type: LazyArg */
3523
3524 /* Excluded from this release type: LifecycleWatcher */
3525
3526 /**
3527 * @public
3528 */
3529 export declare type LowerCasePaperFormat = 'letter' | 'legal' | 'tabloid' | 'ledger' | 'a0' | 'a1' | 'a2' | 'a3' | 'a4' | 'a5' | 'a6';
3530
3531 /* Excluded from this release type: MAIN_WORLD */
3532
3533 /**
3534 * @public
3535 */
3536 export declare interface MediaFeature {
3537 name: string;
3538 value: string;
3539 }
3540
3541 /**
3542 * @public
3543 */
3544 export declare interface Metrics {
3545 Timestamp?: number;
3546 Documents?: number;
3547 Frames?: number;
3548 JSEventListeners?: number;
3549 Nodes?: number;
3550 LayoutCount?: number;
3551 RecalcStyleCount?: number;
3552 LayoutDuration?: number;
3553 RecalcStyleDuration?: number;
3554 ScriptDuration?: number;
3555 TaskDuration?: number;
3556 JSHeapUsedSize?: number;
3557 JSHeapTotalSize?: number;
3558 }
3559
3560 /**
3561 * The Mouse class operates in main-frame CSS pixels
3562 * relative to the top-left corner of the viewport.
3563 * @remarks
3564 * Every `page` object has its own Mouse, accessible with [`page.mouse`](#pagemouse).
3565 *
3566 * @example
3567 *
3568 * ```ts
3569 * // Using ‘page.mouse’ to trace a 100x100 square.
3570 * await page.mouse.move(0, 0);
3571 * await page.mouse.down();
3572 * await page.mouse.move(0, 100);
3573 * await page.mouse.move(100, 100);
3574 * await page.mouse.move(100, 0);
3575 * await page.mouse.move(0, 0);
3576 * await page.mouse.up();
3577 * ```
3578 *
3579 * **Note**: The mouse events trigger synthetic `MouseEvent`s.
3580 * This means that it does not fully replicate the functionality of what a normal user
3581 * would be able to do with their mouse.
3582 *
3583 * For example, dragging and selecting text is not possible using `page.mouse`.
3584 * Instead, you can use the {@link https://developer.mozilla.org/en-US/docs/Web/API/DocumentOrShadowRoot/getSelection | `DocumentOrShadowRoot.getSelection()`} functionality implemented in the platform.
3585 *
3586 * @example
3587 * For example, if you want to select all content between nodes:
3588 *
3589 * ```ts
3590 * await page.evaluate(
3591 * (from, to) => {
3592 * const selection = from.getRootNode().getSelection();
3593 * const range = document.createRange();
3594 * range.setStartBefore(from);
3595 * range.setEndAfter(to);
3596 * selection.removeAllRanges();
3597 * selection.addRange(range);
3598 * },
3599 * fromJSHandle,
3600 * toJSHandle
3601 * );
3602 * ```
3603 *
3604 * If you then would want to copy-paste your selection, you can use the clipboard api:
3605 *
3606 * ```ts
3607 * // The clipboard api does not allow you to copy, unless the tab is focused.
3608 * await page.bringToFront();
3609 * await page.evaluate(() => {
3610 * // Copy the selected content to the clipboard
3611 * document.execCommand('copy');
3612 * // Obtain the content of the clipboard as a string
3613 * return navigator.clipboard.readText();
3614 * });
3615 * ```
3616 *
3617 * **Note**: If you want access to the clipboard API,
3618 * you have to give it permission to do so:
3619 *
3620 * ```ts
3621 * await browser
3622 * .defaultBrowserContext()
3623 * .overridePermissions('<your origin>', [
3624 * 'clipboard-read',
3625 * 'clipboard-write',
3626 * ]);
3627 * ```
3628 *
3629 * @public
3630 */
3631 export declare class Mouse {
3632 #private;
3633 /* Excluded from this release type: __constructor */
3634 /**
3635 * Dispatches a `mousemove` event.
3636 * @param x - Horizontal position of the mouse.
3637 * @param y - Vertical position of the mouse.
3638 * @param options - Optional object. If specified, the `steps` property
3639 * sends intermediate `mousemove` events when set to `1` (default).
3640 */
3641 move(x: number, y: number, options?: {
3642 steps?: number;
3643 }): Promise<void>;
3644 /**
3645 * Shortcut for `mouse.move`, `mouse.down` and `mouse.up`.
3646 * @param x - Horizontal position of the mouse.
3647 * @param y - Vertical position of the mouse.
3648 * @param options - Optional `MouseOptions`.
3649 */
3650 click(x: number, y: number, options?: MouseOptions & {
3651 delay?: number;
3652 }): Promise<void>;
3653 /**
3654 * Dispatches a `mousedown` event.
3655 * @param options - Optional `MouseOptions`.
3656 */
3657 down(options?: MouseOptions): Promise<void>;
3658 /**
3659 * Dispatches a `mouseup` event.
3660 * @param options - Optional `MouseOptions`.
3661 */
3662 up(options?: MouseOptions): Promise<void>;
3663 /**
3664 * Dispatches a `mousewheel` event.
3665 * @param options - Optional: `MouseWheelOptions`.
3666 *
3667 * @example
3668 * An example of zooming into an element:
3669 *
3670 * ```ts
3671 * await page.goto(
3672 * 'https://mdn.mozillademos.org/en-US/docs/Web/API/Element/wheel_event$samples/Scaling_an_element_via_the_wheel?revision=1587366'
3673 * );
3674 *
3675 * const elem = await page.$('div');
3676 * const boundingBox = await elem.boundingBox();
3677 * await page.mouse.move(
3678 * boundingBox.x + boundingBox.width / 2,
3679 * boundingBox.y + boundingBox.height / 2
3680 * );
3681 *
3682 * await page.mouse.wheel({deltaY: -100});
3683 * ```
3684 */
3685 wheel(options?: MouseWheelOptions): Promise<void>;
3686 /**
3687 * Dispatches a `drag` event.
3688 * @param start - starting point for drag
3689 * @param target - point to drag to
3690 */
3691 drag(start: Point, target: Point): Promise<Protocol.Input.DragData>;
3692 /**
3693 * Dispatches a `dragenter` event.
3694 * @param target - point for emitting `dragenter` event
3695 * @param data - drag data containing items and operations mask
3696 */
3697 dragEnter(target: Point, data: Protocol.Input.DragData): Promise<void>;
3698 /**
3699 * Dispatches a `dragover` event.
3700 * @param target - point for emitting `dragover` event
3701 * @param data - drag data containing items and operations mask
3702 */
3703 dragOver(target: Point, data: Protocol.Input.DragData): Promise<void>;
3704 /**
3705 * Performs a dragenter, dragover, and drop in sequence.
3706 * @param target - point to drop on
3707 * @param data - drag data containing items and operations mask
3708 */
3709 drop(target: Point, data: Protocol.Input.DragData): Promise<void>;
3710 /**
3711 * Performs a drag, dragenter, dragover, and drop in sequence.
3712 * @param start - point to drag from
3713 * @param target - point to drop on
3714 * @param options - An object of options. Accepts delay which,
3715 * if specified, is the time to wait between `dragover` and `drop` in milliseconds.
3716 * Defaults to 0.
3717 */
3718 dragAndDrop(start: Point, target: Point, options?: {
3719 delay?: number;
3720 }): Promise<void>;
3721 }
3722
3723 /**
3724 * @public
3725 */
3726 export declare type MouseButton = 'left' | 'right' | 'middle' | 'back' | 'forward';
3727
3728 /**
3729 * @public
3730 */
3731 export declare interface MouseOptions {
3732 button?: MouseButton;
3733 clickCount?: number;
3734 }
3735
3736 /**
3737 * @public
3738 */
3739 export declare interface MouseWheelOptions {
3740 deltaX?: number;
3741 deltaY?: number;
3742 }
3743
3744 /* Excluded from this release type: MutationPoller */
3745
3746 /**
3747 * @public
3748 */
3749 export declare interface NetworkConditions {
3750 download: number;
3751 upload: number;
3752 latency: number;
3753 }
3754
3755 /**
3756 * @deprecated Import {@link PredefinedNetworkConditions}.
3757 *
3758 * @public
3759 */
3760 export declare const networkConditions: Readonly<{
3761 'Slow 3G': NetworkConditions;
3762 'Fast 3G': NetworkConditions;
3763 }>;
3764
3765 /* Excluded from this release type: NetworkEventManager */
3766
3767 /* Excluded from this release type: NetworkManager */
3768
3769 /* Excluded from this release type: NetworkManagerEmittedEvents */
3770
3771 /* Excluded from this release type: NetworkRequestId */
3772
3773 /**
3774 * @public
3775 */
3776 export declare type NodeFor<ComplexSelector extends string> = TypeSelectorOfComplexSelector<ComplexSelector> extends infer TypeSelector ? TypeSelector extends keyof HTMLElementTagNameMap | keyof SVGElementTagNameMap ? ElementFor<TypeSelector> : Element : never;
3777
3778 /* Excluded from this release type: NodeWebSocketTransport */
3779
3780 declare type NonEmptyReadonlyArray<T> = [T, ...(readonly T[])];
3781
3782 /**
3783 * @public
3784 */
3785 export declare interface Offset {
3786 /**
3787 * x-offset for the clickable point relative to the top-left corner of the border box.
3788 */
3789 x: number;
3790 /**
3791 * y-offset for the clickable point relative to the top-left corner of the border box.
3792 */
3793 y: number;
3794 }
3795
3796 /**
3797 * Page provides methods to interact with a single tab or
3798 * {@link https://developer.chrome.com/extensions/background_pages | extension background page}
3799 * in Chromium.
3800 *
3801 * :::note
3802 *
3803 * One Browser instance might have multiple Page instances.
3804 *
3805 * :::
3806 *
3807 * @example
3808 * This example creates a page, navigates it to a URL, and then saves a screenshot:
3809 *
3810 * ```ts
3811 * import puppeteer from 'puppeteer';
3812 *
3813 * (async () => {
3814 * const browser = await puppeteer.launch();
3815 * const page = await browser.newPage();
3816 * await page.goto('https://example.com');
3817 * await page.screenshot({path: 'screenshot.png'});
3818 * await browser.close();
3819 * })();
3820 * ```
3821 *
3822 * The Page class extends from Puppeteer's {@link EventEmitter} class and will
3823 * emit various events which are documented in the {@link PageEmittedEvents} enum.
3824 *
3825 * @example
3826 * This example logs a message for a single page `load` event:
3827 *
3828 * ```ts
3829 * page.once('load', () => console.log('Page loaded!'));
3830 * ```
3831 *
3832 * To unsubscribe from events use the {@link Page.off} method:
3833 *
3834 * ```ts
3835 * function logRequest(interceptedRequest) {
3836 * console.log('A request was made:', interceptedRequest.url());
3837 * }
3838 * page.on('request', logRequest);
3839 * // Sometime later...
3840 * page.off('request', logRequest);
3841 * ```
3842 *
3843 * @public
3844 */
3845 export declare class Page extends EventEmitter {
3846 #private;
3847 /* Excluded from this release type: __constructor */
3848 /**
3849 * @returns `true` if drag events are being intercepted, `false` otherwise.
3850 */
3851 isDragInterceptionEnabled(): boolean;
3852 /**
3853 * @returns `true` if the page has JavaScript enabled, `false` otherwise.
3854 */
3855 isJavaScriptEnabled(): boolean;
3856 /**
3857 * Listen to page events.
3858 *
3859 * :::note
3860 *
3861 * This method exists to define event typings and handle proper wireup of
3862 * cooperative request interception. Actual event listening and dispatching is
3863 * delegated to {@link EventEmitter}.
3864 *
3865 * :::
3866 */
3867 on<K extends keyof PageEventObject>(eventName: K, handler: (event: PageEventObject[K]) => void): EventEmitter;
3868 once<K extends keyof PageEventObject>(eventName: K, handler: (event: PageEventObject[K]) => void): EventEmitter;
3869 off<K extends keyof PageEventObject>(eventName: K, handler: (event: PageEventObject[K]) => void): EventEmitter;
3870 /**
3871 * This method is typically coupled with an action that triggers file
3872 * choosing.
3873 *
3874 * :::caution
3875 *
3876 * This must be called before the file chooser is launched. It will not return
3877 * a currently active file chooser.
3878 *
3879 * :::
3880 *
3881 * @remarks
3882 * In non-headless Chromium, this method results in the native file picker
3883 * dialog `not showing up` for the user.
3884 *
3885 * @example
3886 * The following example clicks a button that issues a file chooser
3887 * and then responds with `/tmp/myfile.pdf` as if a user has selected this file.
3888 *
3889 * ```ts
3890 * const [fileChooser] = await Promise.all([
3891 * page.waitForFileChooser(),
3892 * page.click('#upload-file-button'),
3893 * // some button that triggers file selection
3894 * ]);
3895 * await fileChooser.accept(['/tmp/myfile.pdf']);
3896 * ```
3897 */
3898 waitForFileChooser(options?: WaitTimeoutOptions): Promise<FileChooser>;
3899 /**
3900 * Sets the page's geolocation.
3901 *
3902 * @remarks
3903 * Consider using {@link BrowserContext.overridePermissions} to grant
3904 * permissions for the page to read its geolocation.
3905 *
3906 * @example
3907 *
3908 * ```ts
3909 * await page.setGeolocation({latitude: 59.95, longitude: 30.31667});
3910 * ```
3911 */
3912 setGeolocation(options: GeolocationOptions): Promise<void>;
3913 /**
3914 * @returns A target this page was created from.
3915 */
3916 target(): Target;
3917 /**
3918 * Get the browser the page belongs to.
3919 */
3920 browser(): Browser;
3921 /**
3922 * Get the browser context that the page belongs to.
3923 */
3924 browserContext(): BrowserContext;
3925 /**
3926 * @returns The page's main frame.
3927 *
3928 * @remarks
3929 * Page is guaranteed to have a main frame which persists during navigations.
3930 */
3931 mainFrame(): Frame;
3932 get keyboard(): Keyboard;
3933 get touchscreen(): Touchscreen;
3934 get coverage(): Coverage;
3935 get tracing(): Tracing;
3936 get accessibility(): Accessibility;
3937 /**
3938 * @returns An array of all frames attached to the page.
3939 */
3940 frames(): Frame[];
3941 /**
3942 * @returns all of the dedicated {@link
3943 * https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API |
3944 * WebWorkers} associated with the page.
3945 *
3946 * @remarks
3947 * This does not contain ServiceWorkers
3948 */
3949 workers(): WebWorker[];
3950 /**
3951 * Activating request interception enables {@link HTTPRequest.abort},
3952 * {@link HTTPRequest.continue} and {@link HTTPRequest.respond} methods. This
3953 * provides the capability to modify network requests that are made by a page.
3954 *
3955 * Once request interception is enabled, every request will stall unless it's
3956 * continued, responded or aborted; or completed using the browser cache.
3957 *
3958 * See the
3959 * {@link https://pptr.dev/next/guides/request-interception|Request interception guide}
3960 * for more details.
3961 *
3962 * @example
3963 * An example of a naïve request interceptor that aborts all image requests:
3964 *
3965 * ```ts
3966 * import puppeteer from 'puppeteer';
3967 * (async () => {
3968 * const browser = await puppeteer.launch();
3969 * const page = await browser.newPage();
3970 * await page.setRequestInterception(true);
3971 * page.on('request', interceptedRequest => {
3972 * if (
3973 * interceptedRequest.url().endsWith('.png') ||
3974 * interceptedRequest.url().endsWith('.jpg')
3975 * )
3976 * interceptedRequest.abort();
3977 * else interceptedRequest.continue();
3978 * });
3979 * await page.goto('https://example.com');
3980 * await browser.close();
3981 * })();
3982 * ```
3983 *
3984 * @param value - Whether to enable request interception.
3985 */
3986 setRequestInterception(value: boolean): Promise<void>;
3987 /**
3988 * @param enabled - Whether to enable drag interception.
3989 *
3990 * @remarks
3991 * Activating drag interception enables the `Input.drag`,
3992 * methods This provides the capability to capture drag events emitted
3993 * on the page, which can then be used to simulate drag-and-drop.
3994 */
3995 setDragInterception(enabled: boolean): Promise<void>;
3996 /**
3997 * Sets the network connection to offline.
3998 *
3999 * It does not change the parameters used in {@link Page.emulateNetworkConditions}
4000 *
4001 * @param enabled - When `true`, enables offline mode for the page.
4002 */
4003 setOfflineMode(enabled: boolean): Promise<void>;
4004 /**
4005 * This does not affect WebSockets and WebRTC PeerConnections (see
4006 * https://crbug.com/563644). To set the page offline, you can use
4007 * {@link Page.setOfflineMode}.
4008 *
4009 * A list of predefined network conditions can be used by importing
4010 * {@link PredefinedNetworkConditions}.
4011 *
4012 * @example
4013 *
4014 * ```ts
4015 * import {PredefinedNetworkConditions} from 'puppeteer';
4016 * const slow3G = PredefinedNetworkConditions['Slow 3G'];
4017 *
4018 * (async () => {
4019 * const browser = await puppeteer.launch();
4020 * const page = await browser.newPage();
4021 * await page.emulateNetworkConditions(slow3G);
4022 * await page.goto('https://www.google.com');
4023 * // other actions...
4024 * await browser.close();
4025 * })();
4026 * ```
4027 *
4028 * @param networkConditions - Passing `null` disables network condition
4029 * emulation.
4030 */
4031 emulateNetworkConditions(networkConditions: NetworkConditions | null): Promise<void>;
4032 /**
4033 * This setting will change the default maximum navigation time for the
4034 * following methods and related shortcuts:
4035 *
4036 * - {@link Page.goBack | page.goBack(options)}
4037 *
4038 * - {@link Page.goForward | page.goForward(options)}
4039 *
4040 * - {@link Page.goto | page.goto(url,options)}
4041 *
4042 * - {@link Page.reload | page.reload(options)}
4043 *
4044 * - {@link Page.setContent | page.setContent(html,options)}
4045 *
4046 * - {@link Page.waitForNavigation | page.waitForNavigation(options)}
4047 * @param timeout - Maximum navigation time in milliseconds.
4048 */
4049 setDefaultNavigationTimeout(timeout: number): void;
4050 /**
4051 * @param timeout - Maximum time in milliseconds.
4052 */
4053 setDefaultTimeout(timeout: number): void;
4054 /**
4055 * @returns Maximum time in milliseconds.
4056 */
4057 getDefaultTimeout(): number;
4058 /**
4059 * Runs `document.querySelector` within the page. If no element matches the
4060 * selector, the return value resolves to `null`.
4061 *
4062 * @param selector - A `selector` to query page for
4063 * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | selector}
4064 * to query page for.
4065 */
4066 $<Selector extends string>(selector: Selector): Promise<ElementHandle<NodeFor<Selector>> | null>;
4067 /**
4068 * The method runs `document.querySelectorAll` within the page. If no elements
4069 * match the selector, the return value resolves to `[]`.
4070 * @remarks
4071 * Shortcut for {@link Frame.$$ | Page.mainFrame().$$(selector) }.
4072 * @param selector - A `selector` to query page for
4073 */
4074 $$<Selector extends string>(selector: Selector): Promise<Array<ElementHandle<NodeFor<Selector>>>>;
4075 /**
4076 * @remarks
4077 *
4078 * The only difference between {@link Page.evaluate | page.evaluate} and
4079 * `page.evaluateHandle` is that `evaluateHandle` will return the value
4080 * wrapped in an in-page object.
4081 *
4082 * If the function passed to `page.evaluateHandle` returns a Promise, the
4083 * function will wait for the promise to resolve and return its value.
4084 *
4085 * You can pass a string instead of a function (although functions are
4086 * recommended as they are easier to debug and use with TypeScript):
4087 *
4088 * @example
4089 *
4090 * ```ts
4091 * const aHandle = await page.evaluateHandle('document');
4092 * ```
4093 *
4094 * @example
4095 * {@link JSHandle} instances can be passed as arguments to the `pageFunction`:
4096 *
4097 * ```ts
4098 * const aHandle = await page.evaluateHandle(() => document.body);
4099 * const resultHandle = await page.evaluateHandle(
4100 * body => body.innerHTML,
4101 * aHandle
4102 * );
4103 * console.log(await resultHandle.jsonValue());
4104 * await resultHandle.dispose();
4105 * ```
4106 *
4107 * Most of the time this function returns a {@link JSHandle},
4108 * but if `pageFunction` returns a reference to an element,
4109 * you instead get an {@link ElementHandle} back:
4110 *
4111 * @example
4112 *
4113 * ```ts
4114 * const button = await page.evaluateHandle(() =>
4115 * document.querySelector('button')
4116 * );
4117 * // can call `click` because `button` is an `ElementHandle`
4118 * await button.click();
4119 * ```
4120 *
4121 * The TypeScript definitions assume that `evaluateHandle` returns
4122 * a `JSHandle`, but if you know it's going to return an
4123 * `ElementHandle`, pass it as the generic argument:
4124 *
4125 * ```ts
4126 * const button = await page.evaluateHandle<ElementHandle>(...);
4127 * ```
4128 *
4129 * @param pageFunction - a function that is run within the page
4130 * @param args - arguments to be passed to the pageFunction
4131 */
4132 evaluateHandle<Params extends unknown[], Func extends EvaluateFunc<Params> = EvaluateFunc<Params>>(pageFunction: Func | string, ...args: Params): Promise<HandleFor<Awaited<ReturnType<Func>>>>;
4133 /**
4134 * This method iterates the JavaScript heap and finds all objects with the
4135 * given prototype.
4136 *
4137 * @example
4138 *
4139 * ```ts
4140 * // Create a Map object
4141 * await page.evaluate(() => (window.map = new Map()));
4142 * // Get a handle to the Map object prototype
4143 * const mapPrototype = await page.evaluateHandle(() => Map.prototype);
4144 * // Query all map instances into an array
4145 * const mapInstances = await page.queryObjects(mapPrototype);
4146 * // Count amount of map objects in heap
4147 * const count = await page.evaluate(maps => maps.length, mapInstances);
4148 * await mapInstances.dispose();
4149 * await mapPrototype.dispose();
4150 * ```
4151 *
4152 * @param prototypeHandle - a handle to the object prototype.
4153 * @returns Promise which resolves to a handle to an array of objects with
4154 * this prototype.
4155 */
4156 queryObjects<Prototype>(prototypeHandle: JSHandle<Prototype>): Promise<JSHandle<Prototype[]>>;
4157 /**
4158 * This method runs `document.querySelector` within the page and passes the
4159 * result as the first argument to the `pageFunction`.
4160 *
4161 * @remarks
4162 *
4163 * If no element is found matching `selector`, the method will throw an error.
4164 *
4165 * If `pageFunction` returns a promise `$eval` will wait for the promise to
4166 * resolve and then return its value.
4167 *
4168 * @example
4169 *
4170 * ```ts
4171 * const searchValue = await page.$eval('#search', el => el.value);
4172 * const preloadHref = await page.$eval('link[rel=preload]', el => el.href);
4173 * const html = await page.$eval('.main-container', el => el.outerHTML);
4174 * ```
4175 *
4176 * If you are using TypeScript, you may have to provide an explicit type to the
4177 * first argument of the `pageFunction`.
4178 * By default it is typed as `Element`, but you may need to provide a more
4179 * specific sub-type:
4180 *
4181 * @example
4182 *
4183 * ```ts
4184 * // if you don't provide HTMLInputElement here, TS will error
4185 * // as `value` is not on `Element`
4186 * const searchValue = await page.$eval(
4187 * '#search',
4188 * (el: HTMLInputElement) => el.value
4189 * );
4190 * ```
4191 *
4192 * The compiler should be able to infer the return type
4193 * from the `pageFunction` you provide. If it is unable to, you can use the generic
4194 * type to tell the compiler what return type you expect from `$eval`:
4195 *
4196 * @example
4197 *
4198 * ```ts
4199 * // The compiler can infer the return type in this case, but if it can't
4200 * // or if you want to be more explicit, provide it as the generic type.
4201 * const searchValue = await page.$eval<string>(
4202 * '#search',
4203 * (el: HTMLInputElement) => el.value
4204 * );
4205 * ```
4206 *
4207 * @param selector - the
4208 * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | selector}
4209 * to query for
4210 * @param pageFunction - the function to be evaluated in the page context.
4211 * Will be passed the result of `document.querySelector(selector)` as its
4212 * first argument.
4213 * @param args - any additional arguments to pass through to `pageFunction`.
4214 *
4215 * @returns The result of calling `pageFunction`. If it returns an element it
4216 * is wrapped in an {@link ElementHandle}, else the raw value itself is
4217 * returned.
4218 */
4219 $eval<Selector extends string, Params extends unknown[], Func extends EvaluateFunc<[
4220 ElementHandle<NodeFor<Selector>>,
4221 ...Params
4222 ]> = EvaluateFunc<[ElementHandle<NodeFor<Selector>>, ...Params]>>(selector: Selector, pageFunction: Func | string, ...args: Params): Promise<Awaited<ReturnType<Func>>>;
4223 /**
4224 * This method runs `Array.from(document.querySelectorAll(selector))` within
4225 * the page and passes the result as the first argument to the `pageFunction`.
4226 *
4227 * @remarks
4228 * If `pageFunction` returns a promise `$$eval` will wait for the promise to
4229 * resolve and then return its value.
4230 *
4231 * @example
4232 *
4233 * ```ts
4234 * // get the amount of divs on the page
4235 * const divCount = await page.$$eval('div', divs => divs.length);
4236 *
4237 * // get the text content of all the `.options` elements:
4238 * const options = await page.$$eval('div > span.options', options => {
4239 * return options.map(option => option.textContent);
4240 * });
4241 * ```
4242 *
4243 * If you are using TypeScript, you may have to provide an explicit type to the
4244 * first argument of the `pageFunction`.
4245 * By default it is typed as `Element[]`, but you may need to provide a more
4246 * specific sub-type:
4247 *
4248 * @example
4249 *
4250 * ```ts
4251 * // if you don't provide HTMLInputElement here, TS will error
4252 * // as `value` is not on `Element`
4253 * await page.$$eval('input', (elements: HTMLInputElement[]) => {
4254 * return elements.map(e => e.value);
4255 * });
4256 * ```
4257 *
4258 * The compiler should be able to infer the return type
4259 * from the `pageFunction` you provide. If it is unable to, you can use the generic
4260 * type to tell the compiler what return type you expect from `$$eval`:
4261 *
4262 * @example
4263 *
4264 * ```ts
4265 * // The compiler can infer the return type in this case, but if it can't
4266 * // or if you want to be more explicit, provide it as the generic type.
4267 * const allInputValues = await page.$$eval<string[]>(
4268 * 'input',
4269 * (elements: HTMLInputElement[]) => elements.map(e => e.textContent)
4270 * );
4271 * ```
4272 *
4273 * @param selector - the
4274 * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | selector}
4275 * to query for
4276 * @param pageFunction - the function to be evaluated in the page context.
4277 * Will be passed the result of
4278 * `Array.from(document.querySelectorAll(selector))` as its first argument.
4279 * @param args - any additional arguments to pass through to `pageFunction`.
4280 *
4281 * @returns The result of calling `pageFunction`. If it returns an element it
4282 * is wrapped in an {@link ElementHandle}, else the raw value itself is
4283 * returned.
4284 */
4285 $$eval<Selector extends string, Params extends unknown[], Func extends EvaluateFunc<[
4286 Array<NodeFor<Selector>>,
4287 ...Params
4288 ]> = EvaluateFunc<[Array<NodeFor<Selector>>, ...Params]>>(selector: Selector, pageFunction: Func | string, ...args: Params): Promise<Awaited<ReturnType<Func>>>;
4289 /**
4290 * The method evaluates the XPath expression relative to the page document as
4291 * its context node. If there are no such elements, the method resolves to an
4292 * empty array.
4293 *
4294 * @remarks
4295 * Shortcut for {@link Frame.$x | Page.mainFrame().$x(expression) }.
4296 *
4297 * @param expression - Expression to evaluate
4298 */
4299 $x(expression: string): Promise<Array<ElementHandle<Node>>>;
4300 /**
4301 * If no URLs are specified, this method returns cookies for the current page
4302 * URL. If URLs are specified, only cookies for those URLs are returned.
4303 */
4304 cookies(...urls: string[]): Promise<Protocol.Network.Cookie[]>;
4305 deleteCookie(...cookies: Protocol.Network.DeleteCookiesRequest[]): Promise<void>;
4306 /**
4307 * @example
4308 *
4309 * ```ts
4310 * await page.setCookie(cookieObject1, cookieObject2);
4311 * ```
4312 */
4313 setCookie(...cookies: Protocol.Network.CookieParam[]): Promise<void>;
4314 /**
4315 * Adds a `<script>` tag into the page with the desired URL or content.
4316 *
4317 * @remarks
4318 * Shortcut for
4319 * {@link Frame.addScriptTag | page.mainFrame().addScriptTag(options)}.
4320 *
4321 * @param options - Options for the script.
4322 * @returns An {@link ElementHandle | element handle} to the injected
4323 * `<script>` element.
4324 */
4325 addScriptTag(options: FrameAddScriptTagOptions): Promise<ElementHandle<HTMLScriptElement>>;
4326 /**
4327 * Adds a `<link rel="stylesheet">` tag into the page with the desired URL or
4328 * a `<style type="text/css">` tag with the content.
4329 *
4330 * Shortcut for
4331 * {@link Frame.addStyleTag | page.mainFrame().addStyleTag(options)}.
4332 *
4333 * @returns An {@link ElementHandle | element handle} to the injected `<link>`
4334 * or `<style>` element.
4335 */
4336 addStyleTag(options: Omit<FrameAddStyleTagOptions, 'url'>): Promise<ElementHandle<HTMLStyleElement>>;
4337 addStyleTag(options: FrameAddStyleTagOptions): Promise<ElementHandle<HTMLLinkElement>>;
4338 addStyleTag(options: FrameAddStyleTagOptions): Promise<ElementHandle<HTMLStyleElement | HTMLLinkElement>>;
4339 /**
4340 * The method adds a function called `name` on the page's `window` object.
4341 * When called, the function executes `puppeteerFunction` in node.js and
4342 * returns a `Promise` which resolves to the return value of
4343 * `puppeteerFunction`.
4344 *
4345 * If the puppeteerFunction returns a `Promise`, it will be awaited.
4346 *
4347 * :::note
4348 *
4349 * Functions installed via `page.exposeFunction` survive navigations.
4350 *
4351 * :::note
4352 *
4353 * @example
4354 * An example of adding an `md5` function into the page:
4355 *
4356 * ```ts
4357 * import puppeteer from 'puppeteer';
4358 * import crypto from 'crypto';
4359 *
4360 * (async () => {
4361 * const browser = await puppeteer.launch();
4362 * const page = await browser.newPage();
4363 * page.on('console', msg => console.log(msg.text()));
4364 * await page.exposeFunction('md5', text =>
4365 * crypto.createHash('md5').update(text).digest('hex')
4366 * );
4367 * await page.evaluate(async () => {
4368 * // use window.md5 to compute hashes
4369 * const myString = 'PUPPETEER';
4370 * const myHash = await window.md5(myString);
4371 * console.log(`md5 of ${myString} is ${myHash}`);
4372 * });
4373 * await browser.close();
4374 * })();
4375 * ```
4376 *
4377 * @example
4378 * An example of adding a `window.readfile` function into the page:
4379 *
4380 * ```ts
4381 * import puppeteer from 'puppeteer';
4382 * import fs from 'fs';
4383 *
4384 * (async () => {
4385 * const browser = await puppeteer.launch();
4386 * const page = await browser.newPage();
4387 * page.on('console', msg => console.log(msg.text()));
4388 * await page.exposeFunction('readfile', async filePath => {
4389 * return new Promise((resolve, reject) => {
4390 * fs.readFile(filePath, 'utf8', (err, text) => {
4391 * if (err) reject(err);
4392 * else resolve(text);
4393 * });
4394 * });
4395 * });
4396 * await page.evaluate(async () => {
4397 * // use window.readfile to read contents of a file
4398 * const content = await window.readfile('/etc/hosts');
4399 * console.log(content);
4400 * });
4401 * await browser.close();
4402 * })();
4403 * ```
4404 *
4405 * @param name - Name of the function on the window object
4406 * @param pptrFunction - Callback function which will be called in Puppeteer's
4407 * context.
4408 */
4409 exposeFunction(name: string, pptrFunction: Function | {
4410 default: Function;
4411 }): Promise<void>;
4412 /**
4413 * Provide credentials for `HTTP authentication`.
4414 *
4415 * @remarks
4416 * To disable authentication, pass `null`.
4417 */
4418 authenticate(credentials: Credentials): Promise<void>;
4419 /**
4420 * The extra HTTP headers will be sent with every request the page initiates.
4421 *
4422 * :::tip
4423 *
4424 * All HTTP header names are lowercased. (HTTP headers are
4425 * case-insensitive, so this shouldn’t impact your server code.)
4426 *
4427 * :::
4428 *
4429 * :::note
4430 *
4431 * page.setExtraHTTPHeaders does not guarantee the order of headers in
4432 * the outgoing requests.
4433 *
4434 * :::
4435 *
4436 * @param headers - An object containing additional HTTP headers to be sent
4437 * with every request. All header values must be strings.
4438 */
4439 setExtraHTTPHeaders(headers: Record<string, string>): Promise<void>;
4440 /**
4441 * @param userAgent - Specific user agent to use in this page
4442 * @param userAgentData - Specific user agent client hint data to use in this
4443 * page
4444 * @returns Promise which resolves when the user agent is set.
4445 */
4446 setUserAgent(userAgent: string, userAgentMetadata?: Protocol.Emulation.UserAgentMetadata): Promise<void>;
4447 /**
4448 * @returns Object containing metrics as key/value pairs.
4449 *
4450 * - `Timestamp` : The timestamp when the metrics sample was taken.
4451 *
4452 * - `Documents` : Number of documents in the page.
4453 *
4454 * - `Frames` : Number of frames in the page.
4455 *
4456 * - `JSEventListeners` : Number of events in the page.
4457 *
4458 * - `Nodes` : Number of DOM nodes in the page.
4459 *
4460 * - `LayoutCount` : Total number of full or partial page layout.
4461 *
4462 * - `RecalcStyleCount` : Total number of page style recalculations.
4463 *
4464 * - `LayoutDuration` : Combined durations of all page layouts.
4465 *
4466 * - `RecalcStyleDuration` : Combined duration of all page style
4467 * recalculations.
4468 *
4469 * - `ScriptDuration` : Combined duration of JavaScript execution.
4470 *
4471 * - `TaskDuration` : Combined duration of all tasks performed by the browser.
4472 *
4473 * - `JSHeapUsedSize` : Used JavaScript heap size.
4474 *
4475 * - `JSHeapTotalSize` : Total JavaScript heap size.
4476 *
4477 * @remarks
4478 * All timestamps are in monotonic time: monotonically increasing time
4479 * in seconds since an arbitrary point in the past.
4480 */
4481 metrics(): Promise<Metrics>;
4482 /**
4483 *
4484 * @returns
4485 * @remarks Shortcut for
4486 * {@link Frame.url | page.mainFrame().url()}.
4487 */
4488 url(): string;
4489 content(): Promise<string>;
4490 /**
4491 * @param html - HTML markup to assign to the page.
4492 * @param options - Parameters that has some properties.
4493 * @remarks
4494 * The parameter `options` might have the following options.
4495 *
4496 * - `timeout` : Maximum time in milliseconds for resources to load, defaults
4497 * to 30 seconds, pass `0` to disable timeout. The default value can be
4498 * changed by using the {@link Page.setDefaultNavigationTimeout} or
4499 * {@link Page.setDefaultTimeout} methods.
4500 *
4501 * - `waitUntil`: When to consider setting markup succeeded, defaults to
4502 * `load`. Given an array of event strings, setting content is considered
4503 * to be successful after all events have been fired. Events can be
4504 * either:<br/>
4505 * - `load` : consider setting content to be finished when the `load` event
4506 * is fired.<br/>
4507 * - `domcontentloaded` : consider setting content to be finished when the
4508 * `DOMContentLoaded` event is fired.<br/>
4509 * - `networkidle0` : consider setting content to be finished when there are
4510 * no more than 0 network connections for at least `500` ms.<br/>
4511 * - `networkidle2` : consider setting content to be finished when there are
4512 * no more than 2 network connections for at least `500` ms.
4513 */
4514 setContent(html: string, options?: WaitForOptions): Promise<void>;
4515 /**
4516 * @param url - URL to navigate page to. The URL should include scheme, e.g.
4517 * `https://`
4518 * @param options - Navigation Parameter
4519 * @returns Promise which resolves to the main resource response. In case of
4520 * multiple redirects, the navigation will resolve with the response of the
4521 * last redirect.
4522 * @remarks
4523 * The argument `options` might have the following properties:
4524 *
4525 * - `timeout` : Maximum navigation time in milliseconds, defaults to 30
4526 * seconds, pass 0 to disable timeout. The default value can be changed by
4527 * using the {@link Page.setDefaultNavigationTimeout} or
4528 * {@link Page.setDefaultTimeout} methods.
4529 *
4530 * - `waitUntil`:When to consider navigation succeeded, defaults to `load`.
4531 * Given an array of event strings, navigation is considered to be
4532 * successful after all events have been fired. Events can be either:<br/>
4533 * - `load` : consider navigation to be finished when the load event is
4534 * fired.<br/>
4535 * - `domcontentloaded` : consider navigation to be finished when the
4536 * DOMContentLoaded event is fired.<br/>
4537 * - `networkidle0` : consider navigation to be finished when there are no
4538 * more than 0 network connections for at least `500` ms.<br/>
4539 * - `networkidle2` : consider navigation to be finished when there are no
4540 * more than 2 network connections for at least `500` ms.
4541 *
4542 * - `referer` : Referer header value. If provided it will take preference
4543 * over the referer header value set by
4544 * {@link Page.setExtraHTTPHeaders |page.setExtraHTTPHeaders()}.<br/>
4545 * - `referrerPolicy` : ReferrerPolicy. If provided it will take preference
4546 * over the referer-policy header value set by
4547 * {@link Page.setExtraHTTPHeaders |page.setExtraHTTPHeaders()}.
4548 *
4549 * `page.goto` will throw an error if:
4550 *
4551 * - there's an SSL error (e.g. in case of self-signed certificates).
4552 * - target URL is invalid.
4553 * - the timeout is exceeded during navigation.
4554 * - the remote server does not respond or is unreachable.
4555 * - the main resource failed to load.
4556 *
4557 * `page.goto` will not throw an error when any valid HTTP status code is
4558 * returned by the remote server, including 404 "Not Found" and 500
4559 * "Internal Server Error". The status code for such responses can be
4560 * retrieved by calling response.status().
4561 *
4562 * NOTE: `page.goto` either throws an error or returns a main resource
4563 * response. The only exceptions are navigation to about:blank or navigation
4564 * to the same URL with a different hash, which would succeed and return null.
4565 *
4566 * NOTE: Headless mode doesn't support navigation to a PDF document. See the
4567 * {@link https://bugs.chromium.org/p/chromium/issues/detail?id=761295 |
4568 * upstream issue}.
4569 *
4570 * Shortcut for {@link Frame.goto | page.mainFrame().goto(url, options)}.
4571 */
4572 goto(url: string, options?: WaitForOptions & {
4573 referer?: string;
4574 referrerPolicy?: string;
4575 }): Promise<HTTPResponse | null>;
4576 /**
4577 * @param options - Navigation parameters which might have the following
4578 * properties:
4579 * @returns Promise which resolves to the main resource response. In case of
4580 * multiple redirects, the navigation will resolve with the response of the
4581 * last redirect.
4582 * @remarks
4583 * The argument `options` might have the following properties:
4584 *
4585 * - `timeout` : Maximum navigation time in milliseconds, defaults to 30
4586 * seconds, pass 0 to disable timeout. The default value can be changed by
4587 * using the {@link Page.setDefaultNavigationTimeout} or
4588 * {@link Page.setDefaultTimeout} methods.
4589 *
4590 * - `waitUntil`: When to consider navigation succeeded, defaults to `load`.
4591 * Given an array of event strings, navigation is considered to be
4592 * successful after all events have been fired. Events can be either:<br/>
4593 * - `load` : consider navigation to be finished when the load event is
4594 * fired.<br/>
4595 * - `domcontentloaded` : consider navigation to be finished when the
4596 * DOMContentLoaded event is fired.<br/>
4597 * - `networkidle0` : consider navigation to be finished when there are no
4598 * more than 0 network connections for at least `500` ms.<br/>
4599 * - `networkidle2` : consider navigation to be finished when there are no
4600 * more than 2 network connections for at least `500` ms.
4601 */
4602 reload(options?: WaitForOptions): Promise<HTTPResponse | null>;
4603 /**
4604 * Waits for the page to navigate to a new URL or to reload. It is useful when
4605 * you run code that will indirectly cause the page to navigate.
4606 *
4607 * @example
4608 *
4609 * ```ts
4610 * const [response] = await Promise.all([
4611 * page.waitForNavigation(), // The promise resolves after navigation has finished
4612 * page.click('a.my-link'), // Clicking the link will indirectly cause a navigation
4613 * ]);
4614 * ```
4615 *
4616 * @remarks
4617 * Usage of the
4618 * {@link https://developer.mozilla.org/en-US/docs/Web/API/History_API | History API}
4619 * to change the URL is considered a navigation.
4620 *
4621 * @param options - Navigation parameters which might have the following
4622 * properties:
4623 * @returns A `Promise` which resolves to the main resource response.
4624 *
4625 * - In case of multiple redirects, the navigation will resolve with the
4626 * response of the last redirect.
4627 * - In case of navigation to a different anchor or navigation due to History
4628 * API usage, the navigation will resolve with `null`.
4629 */
4630 waitForNavigation(options?: WaitForOptions): Promise<HTTPResponse | null>;
4631 /**
4632 * @param urlOrPredicate - A URL or predicate to wait for
4633 * @param options - Optional waiting parameters
4634 * @returns Promise which resolves to the matched request
4635 * @example
4636 *
4637 * ```ts
4638 * const firstRequest = await page.waitForRequest(
4639 * 'https://example.com/resource'
4640 * );
4641 * const finalRequest = await page.waitForRequest(
4642 * request => request.url() === 'https://example.com'
4643 * );
4644 * return finalRequest.response()?.ok();
4645 * ```
4646 *
4647 * @remarks
4648 * Optional Waiting Parameters have:
4649 *
4650 * - `timeout`: Maximum wait time in milliseconds, defaults to `30` seconds, pass
4651 * `0` to disable the timeout. The default value can be changed by using the
4652 * {@link Page.setDefaultTimeout} method.
4653 */
4654 waitForRequest(urlOrPredicate: string | ((req: HTTPRequest) => boolean | Promise<boolean>), options?: {
4655 timeout?: number;
4656 }): Promise<HTTPRequest>;
4657 /**
4658 * @param urlOrPredicate - A URL or predicate to wait for.
4659 * @param options - Optional waiting parameters
4660 * @returns Promise which resolves to the matched response.
4661 * @example
4662 *
4663 * ```ts
4664 * const firstResponse = await page.waitForResponse(
4665 * 'https://example.com/resource'
4666 * );
4667 * const finalResponse = await page.waitForResponse(
4668 * response =>
4669 * response.url() === 'https://example.com' && response.status() === 200
4670 * );
4671 * const finalResponse = await page.waitForResponse(async response => {
4672 * return (await response.text()).includes('<html>');
4673 * });
4674 * return finalResponse.ok();
4675 * ```
4676 *
4677 * @remarks
4678 * Optional Parameter have:
4679 *
4680 * - `timeout`: Maximum wait time in milliseconds, defaults to `30` seconds,
4681 * pass `0` to disable the timeout. The default value can be changed by using
4682 * the {@link Page.setDefaultTimeout} method.
4683 */
4684 waitForResponse(urlOrPredicate: string | ((res: HTTPResponse) => boolean | Promise<boolean>), options?: {
4685 timeout?: number;
4686 }): Promise<HTTPResponse>;
4687 /**
4688 * @param options - Optional waiting parameters
4689 * @returns Promise which resolves when network is idle
4690 */
4691 waitForNetworkIdle(options?: {
4692 idleTime?: number;
4693 timeout?: number;
4694 }): Promise<void>;
4695 /**
4696 * @param urlOrPredicate - A URL or predicate to wait for.
4697 * @param options - Optional waiting parameters
4698 * @returns Promise which resolves to the matched frame.
4699 * @example
4700 *
4701 * ```ts
4702 * const frame = await page.waitForFrame(async frame => {
4703 * return frame.name() === 'Test';
4704 * });
4705 * ```
4706 *
4707 * @remarks
4708 * Optional Parameter have:
4709 *
4710 * - `timeout`: Maximum wait time in milliseconds, defaults to `30` seconds,
4711 * pass `0` to disable the timeout. The default value can be changed by using
4712 * the {@link Page.setDefaultTimeout} method.
4713 */
4714 waitForFrame(urlOrPredicate: string | ((frame: Frame) => boolean | Promise<boolean>), options?: {
4715 timeout?: number;
4716 }): Promise<Frame>;
4717 /**
4718 * This method navigate to the previous page in history.
4719 * @param options - Navigation parameters
4720 * @returns Promise which resolves to the main resource response. In case of
4721 * multiple redirects, the navigation will resolve with the response of the
4722 * last redirect. If can not go back, resolves to `null`.
4723 * @remarks
4724 * The argument `options` might have the following properties:
4725 *
4726 * - `timeout` : Maximum navigation time in milliseconds, defaults to 30
4727 * seconds, pass 0 to disable timeout. The default value can be changed by
4728 * using the {@link Page.setDefaultNavigationTimeout} or
4729 * {@link Page.setDefaultTimeout} methods.
4730 *
4731 * - `waitUntil` : When to consider navigation succeeded, defaults to `load`.
4732 * Given an array of event strings, navigation is considered to be
4733 * successful after all events have been fired. Events can be either:<br/>
4734 * - `load` : consider navigation to be finished when the load event is
4735 * fired.<br/>
4736 * - `domcontentloaded` : consider navigation to be finished when the
4737 * DOMContentLoaded event is fired.<br/>
4738 * - `networkidle0` : consider navigation to be finished when there are no
4739 * more than 0 network connections for at least `500` ms.<br/>
4740 * - `networkidle2` : consider navigation to be finished when there are no
4741 * more than 2 network connections for at least `500` ms.
4742 */
4743 goBack(options?: WaitForOptions): Promise<HTTPResponse | null>;
4744 /**
4745 * This method navigate to the next page in history.
4746 * @param options - Navigation Parameter
4747 * @returns Promise which resolves to the main resource response. In case of
4748 * multiple redirects, the navigation will resolve with the response of the
4749 * last redirect. If can not go forward, resolves to `null`.
4750 * @remarks
4751 * The argument `options` might have the following properties:
4752 *
4753 * - `timeout` : Maximum navigation time in milliseconds, defaults to 30
4754 * seconds, pass 0 to disable timeout. The default value can be changed by
4755 * using the {@link Page.setDefaultNavigationTimeout} or
4756 * {@link Page.setDefaultTimeout} methods.
4757 *
4758 * - `waitUntil`: When to consider navigation succeeded, defaults to `load`.
4759 * Given an array of event strings, navigation is considered to be
4760 * successful after all events have been fired. Events can be either:<br/>
4761 * - `load` : consider navigation to be finished when the load event is
4762 * fired.<br/>
4763 * - `domcontentloaded` : consider navigation to be finished when the
4764 * DOMContentLoaded event is fired.<br/>
4765 * - `networkidle0` : consider navigation to be finished when there are no
4766 * more than 0 network connections for at least `500` ms.<br/>
4767 * - `networkidle2` : consider navigation to be finished when there are no
4768 * more than 2 network connections for at least `500` ms.
4769 */
4770 goForward(options?: WaitForOptions): Promise<HTTPResponse | null>;
4771 /**
4772 * Brings page to front (activates tab).
4773 */
4774 bringToFront(): Promise<void>;
4775 /**
4776 * Emulates a given device's metrics and user agent.
4777 *
4778 * To aid emulation, Puppeteer provides a list of known devices that can be
4779 * via {@link KnownDevices}.
4780 *
4781 * @remarks
4782 * This method is a shortcut for calling two methods:
4783 * {@link Page.setUserAgent} and {@link Page.setViewport}.
4784 *
4785 * @remarks
4786 * This method will resize the page. A lot of websites don't expect phones to
4787 * change size, so you should emulate before navigating to the page.
4788 *
4789 * @example
4790 *
4791 * ```ts
4792 * import {KnownDevices} from 'puppeteer';
4793 * const iPhone = KnownDevices['iPhone 6'];
4794 *
4795 * (async () => {
4796 * const browser = await puppeteer.launch();
4797 * const page = await browser.newPage();
4798 * await page.emulate(iPhone);
4799 * await page.goto('https://www.google.com');
4800 * // other actions...
4801 * await browser.close();
4802 * })();
4803 * ```
4804 */
4805 emulate(device: Device): Promise<void>;
4806 /**
4807 * @param enabled - Whether or not to enable JavaScript on the page.
4808 * @remarks
4809 * NOTE: changing this value won't affect scripts that have already been run.
4810 * It will take full effect on the next navigation.
4811 */
4812 setJavaScriptEnabled(enabled: boolean): Promise<void>;
4813 /**
4814 * Toggles bypassing page's Content-Security-Policy.
4815 * @param enabled - sets bypassing of page's Content-Security-Policy.
4816 * @remarks
4817 * NOTE: CSP bypassing happens at the moment of CSP initialization rather than
4818 * evaluation. Usually, this means that `page.setBypassCSP` should be called
4819 * before navigating to the domain.
4820 */
4821 setBypassCSP(enabled: boolean): Promise<void>;
4822 /**
4823 * @param type - Changes the CSS media type of the page. The only allowed
4824 * values are `screen`, `print` and `null`. Passing `null` disables CSS media
4825 * emulation.
4826 * @example
4827 *
4828 * ```ts
4829 * await page.evaluate(() => matchMedia('screen').matches);
4830 * // → true
4831 * await page.evaluate(() => matchMedia('print').matches);
4832 * // → false
4833 *
4834 * await page.emulateMediaType('print');
4835 * await page.evaluate(() => matchMedia('screen').matches);
4836 * // → false
4837 * await page.evaluate(() => matchMedia('print').matches);
4838 * // → true
4839 *
4840 * await page.emulateMediaType(null);
4841 * await page.evaluate(() => matchMedia('screen').matches);
4842 * // → true
4843 * await page.evaluate(() => matchMedia('print').matches);
4844 * // → false
4845 * ```
4846 */
4847 emulateMediaType(type?: string): Promise<void>;
4848 /**
4849 * Enables CPU throttling to emulate slow CPUs.
4850 * @param factor - slowdown factor (1 is no throttle, 2 is 2x slowdown, etc).
4851 */
4852 emulateCPUThrottling(factor: number | null): Promise<void>;
4853 /**
4854 * @param features - `<?Array<Object>>` Given an array of media feature
4855 * objects, emulates CSS media features on the page. Each media feature object
4856 * must have the following properties:
4857 * @example
4858 *
4859 * ```ts
4860 * await page.emulateMediaFeatures([
4861 * {name: 'prefers-color-scheme', value: 'dark'},
4862 * ]);
4863 * await page.evaluate(
4864 * () => matchMedia('(prefers-color-scheme: dark)').matches
4865 * );
4866 * // → true
4867 * await page.evaluate(
4868 * () => matchMedia('(prefers-color-scheme: light)').matches
4869 * );
4870 * // → false
4871 *
4872 * await page.emulateMediaFeatures([
4873 * {name: 'prefers-reduced-motion', value: 'reduce'},
4874 * ]);
4875 * await page.evaluate(
4876 * () => matchMedia('(prefers-reduced-motion: reduce)').matches
4877 * );
4878 * // → true
4879 * await page.evaluate(
4880 * () => matchMedia('(prefers-reduced-motion: no-preference)').matches
4881 * );
4882 * // → false
4883 *
4884 * await page.emulateMediaFeatures([
4885 * {name: 'prefers-color-scheme', value: 'dark'},
4886 * {name: 'prefers-reduced-motion', value: 'reduce'},
4887 * ]);
4888 * await page.evaluate(
4889 * () => matchMedia('(prefers-color-scheme: dark)').matches
4890 * );
4891 * // → true
4892 * await page.evaluate(
4893 * () => matchMedia('(prefers-color-scheme: light)').matches
4894 * );
4895 * // → false
4896 * await page.evaluate(
4897 * () => matchMedia('(prefers-reduced-motion: reduce)').matches
4898 * );
4899 * // → true
4900 * await page.evaluate(
4901 * () => matchMedia('(prefers-reduced-motion: no-preference)').matches
4902 * );
4903 * // → false
4904 *
4905 * await page.emulateMediaFeatures([{name: 'color-gamut', value: 'p3'}]);
4906 * await page.evaluate(() => matchMedia('(color-gamut: srgb)').matches);
4907 * // → true
4908 * await page.evaluate(() => matchMedia('(color-gamut: p3)').matches);
4909 * // → true
4910 * await page.evaluate(() => matchMedia('(color-gamut: rec2020)').matches);
4911 * // → false
4912 * ```
4913 */
4914 emulateMediaFeatures(features?: MediaFeature[]): Promise<void>;
4915 /**
4916 * @param timezoneId - Changes the timezone of the page. See
4917 * {@link https://source.chromium.org/chromium/chromium/deps/icu.git/+/faee8bc70570192d82d2978a71e2a615788597d1:source/data/misc/metaZones.txt | ICU’s metaZones.txt}
4918 * for a list of supported timezone IDs. Passing
4919 * `null` disables timezone emulation.
4920 */
4921 emulateTimezone(timezoneId?: string): Promise<void>;
4922 /**
4923 * Emulates the idle state.
4924 * If no arguments set, clears idle state emulation.
4925 *
4926 * @example
4927 *
4928 * ```ts
4929 * // set idle emulation
4930 * await page.emulateIdleState({isUserActive: true, isScreenUnlocked: false});
4931 *
4932 * // do some checks here
4933 * ...
4934 *
4935 * // clear idle emulation
4936 * await page.emulateIdleState();
4937 * ```
4938 *
4939 * @param overrides - Mock idle state. If not set, clears idle overrides
4940 */
4941 emulateIdleState(overrides?: {
4942 isUserActive: boolean;
4943 isScreenUnlocked: boolean;
4944 }): Promise<void>;
4945 /**
4946 * Simulates the given vision deficiency on the page.
4947 *
4948 * @example
4949 *
4950 * ```ts
4951 * import puppeteer from 'puppeteer';
4952 *
4953 * (async () => {
4954 * const browser = await puppeteer.launch();
4955 * const page = await browser.newPage();
4956 * await page.goto('https://v8.dev/blog/10-years');
4957 *
4958 * await page.emulateVisionDeficiency('achromatopsia');
4959 * await page.screenshot({path: 'achromatopsia.png'});
4960 *
4961 * await page.emulateVisionDeficiency('deuteranopia');
4962 * await page.screenshot({path: 'deuteranopia.png'});
4963 *
4964 * await page.emulateVisionDeficiency('blurredVision');
4965 * await page.screenshot({path: 'blurred-vision.png'});
4966 *
4967 * await browser.close();
4968 * })();
4969 * ```
4970 *
4971 * @param type - the type of deficiency to simulate, or `'none'` to reset.
4972 */
4973 emulateVisionDeficiency(type?: Protocol.Emulation.SetEmulatedVisionDeficiencyRequest['type']): Promise<void>;
4974 /**
4975 * `page.setViewport` will resize the page. A lot of websites don't expect
4976 * phones to change size, so you should set the viewport before navigating to
4977 * the page.
4978 *
4979 * In the case of multiple pages in a single browser, each page can have its
4980 * own viewport size.
4981 * @example
4982 *
4983 * ```ts
4984 * const page = await browser.newPage();
4985 * await page.setViewport({
4986 * width: 640,
4987 * height: 480,
4988 * deviceScaleFactor: 1,
4989 * });
4990 * await page.goto('https://example.com');
4991 * ```
4992 *
4993 * @param viewport -
4994 * @remarks
4995 * Argument viewport have following properties:
4996 *
4997 * - `width`: page width in pixels. required
4998 *
4999 * - `height`: page height in pixels. required
5000 *
5001 * - `deviceScaleFactor`: Specify device scale factor (can be thought of as
5002 * DPR). Defaults to `1`.
5003 *
5004 * - `isMobile`: Whether the meta viewport tag is taken into account. Defaults
5005 * to `false`.
5006 *
5007 * - `hasTouch`: Specifies if viewport supports touch events. Defaults to `false`
5008 *
5009 * - `isLandScape`: Specifies if viewport is in landscape mode. Defaults to false.
5010 *
5011 * NOTE: in certain cases, setting viewport will reload the page in order to
5012 * set the isMobile or hasTouch properties.
5013 */
5014 setViewport(viewport: Viewport): Promise<void>;
5015 /**
5016 * @returns
5017 *
5018 * - `width`: page's width in pixels
5019 *
5020 * - `height`: page's height in pixels
5021 *
5022 * - `deviceScaleFactor`: Specify device scale factor (can be though of as
5023 * dpr). Defaults to `1`.
5024 *
5025 * - `isMobile`: Whether the meta viewport tag is taken into account. Defaults
5026 * to `false`.
5027 *
5028 * - `hasTouch`: Specifies if viewport supports touch events. Defaults to
5029 * `false`.
5030 *
5031 * - `isLandScape`: Specifies if viewport is in landscape mode. Defaults to
5032 * `false`.
5033 */
5034 viewport(): Viewport | null;
5035 /**
5036 * Evaluates a function in the page's context and returns the result.
5037 *
5038 * If the function passed to `page.evaluateHandle` returns a Promise, the
5039 * function will wait for the promise to resolve and return its value.
5040 *
5041 * @example
5042 *
5043 * ```ts
5044 * const result = await frame.evaluate(() => {
5045 * return Promise.resolve(8 * 7);
5046 * });
5047 * console.log(result); // prints "56"
5048 * ```
5049 *
5050 * You can pass a string instead of a function (although functions are
5051 * recommended as they are easier to debug and use with TypeScript):
5052 *
5053 * @example
5054 *
5055 * ```ts
5056 * const aHandle = await page.evaluate('1 + 2');
5057 * ```
5058 *
5059 * To get the best TypeScript experience, you should pass in as the
5060 * generic the type of `pageFunction`:
5061 *
5062 * ```ts
5063 * const aHandle = await page.evaluate(() => 2);
5064 * ```
5065 *
5066 * @example
5067 *
5068 * {@link ElementHandle} instances (including {@link JSHandle}s) can be passed
5069 * as arguments to the `pageFunction`:
5070 *
5071 * ```ts
5072 * const bodyHandle = await page.$('body');
5073 * const html = await page.evaluate(body => body.innerHTML, bodyHandle);
5074 * await bodyHandle.dispose();
5075 * ```
5076 *
5077 * @param pageFunction - a function that is run within the page
5078 * @param args - arguments to be passed to the pageFunction
5079 *
5080 * @returns the return value of `pageFunction`.
5081 */
5082 evaluate<Params extends unknown[], Func extends EvaluateFunc<Params> = EvaluateFunc<Params>>(pageFunction: Func | string, ...args: Params): Promise<Awaited<ReturnType<Func>>>;
5083 /**
5084 * Adds a function which would be invoked in one of the following scenarios:
5085 *
5086 * - whenever the page is navigated
5087 *
5088 * - whenever the child frame is attached or navigated. In this case, the
5089 * function is invoked in the context of the newly attached frame.
5090 *
5091 * The function is invoked after the document was created but before any of
5092 * its scripts were run. This is useful to amend the JavaScript environment,
5093 * e.g. to seed `Math.random`.
5094 * @param pageFunction - Function to be evaluated in browser context
5095 * @param args - Arguments to pass to `pageFunction`
5096 * @example
5097 * An example of overriding the navigator.languages property before the page loads:
5098 *
5099 * ```ts
5100 * // preload.js
5101 *
5102 * // overwrite the `languages` property to use a custom getter
5103 * Object.defineProperty(navigator, 'languages', {
5104 * get: function () {
5105 * return ['en-US', 'en', 'bn'];
5106 * },
5107 * });
5108 *
5109 * // In your puppeteer script, assuming the preload.js file is
5110 * // in same folder of our script.
5111 * const preloadFile = fs.readFileSync('./preload.js', 'utf8');
5112 * await page.evaluateOnNewDocument(preloadFile);
5113 * ```
5114 */
5115 evaluateOnNewDocument<Params extends unknown[], Func extends (...args: Params) => unknown = (...args: Params) => unknown>(pageFunction: Func | string, ...args: Params): Promise<void>;
5116 /**
5117 * Toggles ignoring cache for each request based on the enabled state. By
5118 * default, caching is enabled.
5119 * @param enabled - sets the `enabled` state of cache
5120 * @defaultValue true
5121 */
5122 setCacheEnabled(enabled?: boolean): Promise<void>;
5123 /**
5124 * @remarks
5125 * Options object which might have the following properties:
5126 *
5127 * - `path` : The file path to save the image to. The screenshot type
5128 * will be inferred from file extension. If `path` is a relative path, then
5129 * it is resolved relative to
5130 * {@link https://nodejs.org/api/process.html#process_process_cwd
5131 * | current working directory}.
5132 * If no path is provided, the image won't be saved to the disk.
5133 *
5134 * - `type` : Specify screenshot type, can be either `jpeg` or `png`.
5135 * Defaults to 'png'.
5136 *
5137 * - `quality` : The quality of the image, between 0-100. Not
5138 * applicable to `png` images.
5139 *
5140 * - `fullPage` : When true, takes a screenshot of the full
5141 * scrollable page. Defaults to `false`.
5142 *
5143 * - `clip` : An object which specifies clipping region of the page.
5144 * Should have the following fields:<br/>
5145 * - `x` : x-coordinate of top-left corner of clip area.<br/>
5146 * - `y` : y-coordinate of top-left corner of clip area.<br/>
5147 * - `width` : width of clipping area.<br/>
5148 * - `height` : height of clipping area.
5149 *
5150 * - `omitBackground` : Hides default white background and allows
5151 * capturing screenshots with transparency. Defaults to `false`.
5152 *
5153 * - `encoding` : The encoding of the image, can be either base64 or
5154 * binary. Defaults to `binary`.
5155 *
5156 * - `captureBeyondViewport` : When true, captures screenshot
5157 * {@link https://chromedevtools.github.io/devtools-protocol/tot/Page/#method-captureScreenshot
5158 * | beyond the viewport}. When false, falls back to old behaviour,
5159 * and cuts the screenshot by the viewport size. Defaults to `true`.
5160 *
5161 * - `fromSurface` : When true, captures screenshot
5162 * {@link https://chromedevtools.github.io/devtools-protocol/tot/Page/#method-captureScreenshot
5163 * | from the surface rather than the view}. When false, works only in
5164 * headful mode and ignores page viewport (but not browser window's
5165 * bounds). Defaults to `true`.
5166 *
5167 * NOTE: Screenshots take at least 1/6 second on OS X. See
5168 * {@link https://crbug.com/741689} for discussion.
5169 * @returns Promise which resolves to buffer or a base64 string (depending on
5170 * the value of `encoding`) with captured screenshot.
5171 */
5172 screenshot(options: ScreenshotOptions & {
5173 encoding: 'base64';
5174 }): Promise<string>;
5175 screenshot(options?: ScreenshotOptions & {
5176 encoding?: 'binary';
5177 }): Promise<Buffer>;
5178 screenshot(options?: ScreenshotOptions): Promise<Buffer | string>;
5179 /**
5180 * Generates a PDF of the page with the `print` CSS media type.
5181 * @remarks
5182 *
5183 * NOTE: PDF generation is only supported in Chrome headless mode.
5184 *
5185 * To generate a PDF with the `screen` media type, call
5186 * {@link Page.emulateMediaType | `page.emulateMediaType('screen')`} before
5187 * calling `page.pdf()`.
5188 *
5189 * By default, `page.pdf()` generates a pdf with modified colors for printing.
5190 * Use the
5191 * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/-webkit-print-color-adjust | `-webkit-print-color-adjust`}
5192 * property to force rendering of exact colors.
5193 *
5194 * @param options - options for generating the PDF.
5195 */
5196 createPDFStream(options?: PDFOptions): Promise<Readable>;
5197 /**
5198 * @param options -
5199 * @returns
5200 */
5201 pdf(options?: PDFOptions): Promise<Buffer>;
5202 /**
5203 * @returns The page's title
5204 * @remarks
5205 * Shortcut for {@link Frame.title | page.mainFrame().title()}.
5206 */
5207 title(): Promise<string>;
5208 close(options?: {
5209 runBeforeUnload?: boolean;
5210 }): Promise<void>;
5211 /**
5212 * Indicates that the page has been closed.
5213 * @returns
5214 */
5215 isClosed(): boolean;
5216 get mouse(): Mouse;
5217 /**
5218 * This method fetches an element with `selector`, scrolls it into view if
5219 * needed, and then uses {@link Page.mouse} to click in the center of the
5220 * element. If there's no element matching `selector`, the method throws an
5221 * error.
5222 * @remarks Bear in mind that if `click()` triggers a navigation event and
5223 * there's a separate `page.waitForNavigation()` promise to be resolved, you
5224 * may end up with a race condition that yields unexpected results. The
5225 * correct pattern for click and wait for navigation is the following:
5226 *
5227 * ```ts
5228 * const [response] = await Promise.all([
5229 * page.waitForNavigation(waitOptions),
5230 * page.click(selector, clickOptions),
5231 * ]);
5232 * ```
5233 *
5234 * Shortcut for {@link Frame.click | page.mainFrame().click(selector[, options]) }.
5235 * @param selector - A `selector` to search for element to click. If there are
5236 * multiple elements satisfying the `selector`, the first will be clicked
5237 * @param options - `Object`
5238 * @returns Promise which resolves when the element matching `selector` is
5239 * successfully clicked. The Promise will be rejected if there is no element
5240 * matching `selector`.
5241 */
5242 click(selector: string, options?: {
5243 delay?: number;
5244 button?: MouseButton;
5245 clickCount?: number;
5246 }): Promise<void>;
5247 /**
5248 * This method fetches an element with `selector` and focuses it. If there's no
5249 * element matching `selector`, the method throws an error.
5250 * @param selector - A
5251 * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | selector }
5252 * of an element to focus. If there are multiple elements satisfying the
5253 * selector, the first will be focused.
5254 * @returns Promise which resolves when the element matching selector is
5255 * successfully focused. The promise will be rejected if there is no element
5256 * matching selector.
5257 * @remarks
5258 * Shortcut for {@link Frame.focus | page.mainFrame().focus(selector)}.
5259 */
5260 focus(selector: string): Promise<void>;
5261 /**
5262 * This method fetches an element with `selector`, scrolls it into view if
5263 * needed, and then uses {@link Page.mouse} to hover over the center of the element.
5264 * If there's no element matching `selector`, the method throws an error.
5265 * @param selector - A
5266 * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | selector}
5267 * to search for element to hover. If there are multiple elements satisfying
5268 * the selector, the first will be hovered.
5269 * @returns Promise which resolves when the element matching `selector` is
5270 * successfully hovered. Promise gets rejected if there's no element matching
5271 * `selector`.
5272 * @remarks
5273 * Shortcut for {@link Page.hover | page.mainFrame().hover(selector)}.
5274 */
5275 hover(selector: string): Promise<void>;
5276 /**
5277 * Triggers a `change` and `input` event once all the provided options have been
5278 * selected. If there's no `<select>` element matching `selector`, the method
5279 * throws an error.
5280 *
5281 * @example
5282 *
5283 * ```ts
5284 * page.select('select#colors', 'blue'); // single selection
5285 * page.select('select#colors', 'red', 'green', 'blue'); // multiple selections
5286 * ```
5287 *
5288 * @param selector - A
5289 * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | Selector}
5290 * to query the page for
5291 * @param values - Values of options to select. If the `<select>` has the
5292 * `multiple` attribute, all values are considered, otherwise only the first one
5293 * is taken into account.
5294 * @returns
5295 *
5296 * @remarks
5297 * Shortcut for {@link Frame.select | page.mainFrame().select()}
5298 */
5299 select(selector: string, ...values: string[]): Promise<string[]>;
5300 /**
5301 * This method fetches an element with `selector`, scrolls it into view if
5302 * needed, and then uses {@link Page.touchscreen} to tap in the center of the element.
5303 * If there's no element matching `selector`, the method throws an error.
5304 * @param selector - A
5305 * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | Selector}
5306 * to search for element to tap. If there are multiple elements satisfying the
5307 * selector, the first will be tapped.
5308 * @returns
5309 * @remarks
5310 * Shortcut for {@link Frame.tap | page.mainFrame().tap(selector)}.
5311 */
5312 tap(selector: string): Promise<void>;
5313 /**
5314 * Sends a `keydown`, `keypress/input`, and `keyup` event for each character
5315 * in the text.
5316 *
5317 * To press a special key, like `Control` or `ArrowDown`, use {@link Keyboard.press}.
5318 * @example
5319 *
5320 * ```ts
5321 * await page.type('#mytextarea', 'Hello');
5322 * // Types instantly
5323 * await page.type('#mytextarea', 'World', {delay: 100});
5324 * // Types slower, like a user
5325 * ```
5326 *
5327 * @param selector - A
5328 * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | selector}
5329 * of an element to type into. If there are multiple elements satisfying the
5330 * selector, the first will be used.
5331 * @param text - A text to type into a focused element.
5332 * @param options - have property `delay` which is the Time to wait between
5333 * key presses in milliseconds. Defaults to `0`.
5334 * @returns
5335 * @remarks
5336 */
5337 type(selector: string, text: string, options?: {
5338 delay: number;
5339 }): Promise<void>;
5340 /**
5341 * @deprecated Replace with `new Promise(r => setTimeout(r, milliseconds));`.
5342 *
5343 * Causes your script to wait for the given number of milliseconds.
5344 *
5345 * @remarks
5346 * It's generally recommended to not wait for a number of seconds, but instead
5347 * use {@link Frame.waitForSelector}, {@link Frame.waitForXPath} or
5348 * {@link Frame.waitForFunction} to wait for exactly the conditions you want.
5349 *
5350 * @example
5351 *
5352 * Wait for 1 second:
5353 *
5354 * ```ts
5355 * await page.waitForTimeout(1000);
5356 * ```
5357 *
5358 * @param milliseconds - the number of milliseconds to wait.
5359 */
5360 waitForTimeout(milliseconds: number): Promise<void>;
5361 /**
5362 * Wait for the `selector` to appear in page. If at the moment of calling the
5363 * method the `selector` already exists, the method will return immediately. If
5364 * the `selector` doesn't appear after the `timeout` milliseconds of waiting, the
5365 * function will throw.
5366 *
5367 * This method works across navigations:
5368 *
5369 * ```ts
5370 * import puppeteer from 'puppeteer';
5371 * (async () => {
5372 * const browser = await puppeteer.launch();
5373 * const page = await browser.newPage();
5374 * let currentURL;
5375 * page
5376 * .waitForSelector('img')
5377 * .then(() => console.log('First URL with image: ' + currentURL));
5378 * for (currentURL of [
5379 * 'https://example.com',
5380 * 'https://google.com',
5381 * 'https://bbc.com',
5382 * ]) {
5383 * await page.goto(currentURL);
5384 * }
5385 * await browser.close();
5386 * })();
5387 * ```
5388 *
5389 * @param selector - A
5390 * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | selector}
5391 * of an element to wait for
5392 * @param options - Optional waiting parameters
5393 * @returns Promise which resolves when element specified by selector string
5394 * is added to DOM. Resolves to `null` if waiting for hidden: `true` and
5395 * selector is not found in DOM.
5396 * @remarks
5397 * The optional Parameter in Arguments `options` are:
5398 *
5399 * - `visible`: A boolean wait for element to be present in DOM and to be
5400 * visible, i.e. to not have `display: none` or `visibility: hidden` CSS
5401 * properties. Defaults to `false`.
5402 *
5403 * - `hidden`: Wait for element to not be found in the DOM or to be hidden,
5404 * i.e. have `display: none` or `visibility: hidden` CSS properties. Defaults to
5405 * `false`.
5406 *
5407 * - `timeout`: maximum time to wait for in milliseconds. Defaults to `30000`
5408 * (30 seconds). Pass `0` to disable timeout. The default value can be changed
5409 * by using the {@link Page.setDefaultTimeout} method.
5410 */
5411 waitForSelector<Selector extends string>(selector: Selector, options?: WaitForSelectorOptions): Promise<ElementHandle<NodeFor<Selector>> | null>;
5412 /**
5413 * Wait for the `xpath` to appear in page. If at the moment of calling the
5414 * method the `xpath` already exists, the method will return immediately. If
5415 * the `xpath` doesn't appear after the `timeout` milliseconds of waiting, the
5416 * function will throw.
5417 *
5418 * This method works across navigation
5419 *
5420 * ```ts
5421 * import puppeteer from 'puppeteer';
5422 * (async () => {
5423 * const browser = await puppeteer.launch();
5424 * const page = await browser.newPage();
5425 * let currentURL;
5426 * page
5427 * .waitForXPath('//img')
5428 * .then(() => console.log('First URL with image: ' + currentURL));
5429 * for (currentURL of [
5430 * 'https://example.com',
5431 * 'https://google.com',
5432 * 'https://bbc.com',
5433 * ]) {
5434 * await page.goto(currentURL);
5435 * }
5436 * await browser.close();
5437 * })();
5438 * ```
5439 *
5440 * @param xpath - A
5441 * {@link https://developer.mozilla.org/en-US/docs/Web/XPath | xpath} of an
5442 * element to wait for
5443 * @param options - Optional waiting parameters
5444 * @returns Promise which resolves when element specified by xpath string is
5445 * added to DOM. Resolves to `null` if waiting for `hidden: true` and xpath is
5446 * not found in DOM.
5447 * @remarks
5448 * The optional Argument `options` have properties:
5449 *
5450 * - `visible`: A boolean to wait for element to be present in DOM and to be
5451 * visible, i.e. to not have `display: none` or `visibility: hidden` CSS
5452 * properties. Defaults to `false`.
5453 *
5454 * - `hidden`: A boolean wait for element to not be found in the DOM or to be
5455 * hidden, i.e. have `display: none` or `visibility: hidden` CSS properties.
5456 * Defaults to `false`.
5457 *
5458 * - `timeout`: A number which is maximum time to wait for in milliseconds.
5459 * Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default
5460 * value can be changed by using the {@link Page.setDefaultTimeout} method.
5461 */
5462 waitForXPath(xpath: string, options?: {
5463 visible?: boolean;
5464 hidden?: boolean;
5465 timeout?: number;
5466 }): Promise<ElementHandle<Node> | null>;
5467 /**
5468 * Waits for a function to finish evaluating in the page's context.
5469 *
5470 * @example
5471 * The {@link Page.waitForFunction} can be used to observe viewport size change:
5472 *
5473 * ```ts
5474 * import puppeteer from 'puppeteer';
5475 * (async () => {
5476 * const browser = await puppeteer.launch();
5477 * const page = await browser.newPage();
5478 * const watchDog = page.waitForFunction('window.innerWidth < 100');
5479 * await page.setViewport({width: 50, height: 50});
5480 * await watchDog;
5481 * await browser.close();
5482 * })();
5483 * ```
5484 *
5485 * @example
5486 * To pass arguments from node.js to the predicate of
5487 * {@link Page.waitForFunction} function:
5488 *
5489 * ```ts
5490 * const selector = '.foo';
5491 * await page.waitForFunction(
5492 * selector => !!document.querySelector(selector),
5493 * {},
5494 * selector
5495 * );
5496 * ```
5497 *
5498 * @example
5499 * The predicate of {@link Page.waitForFunction} can be asynchronous too:
5500 *
5501 * ```ts
5502 * const username = 'github-username';
5503 * await page.waitForFunction(
5504 * async username => {
5505 * const githubResponse = await fetch(
5506 * `https://api.github.com/users/${username}`
5507 * );
5508 * const githubUser = await githubResponse.json();
5509 * // show the avatar
5510 * const img = document.createElement('img');
5511 * img.src = githubUser.avatar_url;
5512 * // wait 3 seconds
5513 * await new Promise((resolve, reject) => setTimeout(resolve, 3000));
5514 * img.remove();
5515 * },
5516 * {},
5517 * username
5518 * );
5519 * ```
5520 *
5521 * @param pageFunction - Function to be evaluated in browser context
5522 * @param options - Options for configuring waiting behavior.
5523 */
5524 waitForFunction<Params extends unknown[], Func extends EvaluateFunc<Params> = EvaluateFunc<Params>>(pageFunction: Func | string, options?: FrameWaitForFunctionOptions, ...args: Params): Promise<HandleFor<Awaited<ReturnType<Func>>>>;
5525 }
5526
5527 /* Excluded from this release type: PageBinding */
5528
5529 /* Excluded from this release type: pageBindingDeliverErrorString */
5530
5531 /* Excluded from this release type: pageBindingDeliverErrorValueString */
5532
5533 /* Excluded from this release type: pageBindingDeliverResultString */
5534
5535 /* Excluded from this release type: pageBindingInitString */
5536
5537 /**
5538 * All the events that a page instance may emit.
5539 *
5540 * @public
5541 */
5542 export declare const enum PageEmittedEvents {
5543 /**
5544 * Emitted when the page closes.
5545 * @eventProperty
5546 */
5547 Close = "close",
5548 /**
5549 * Emitted when JavaScript within the page calls one of console API methods,
5550 * e.g. `console.log` or `console.dir`. Also emitted if the page throws an
5551 * error or a warning.
5552 *
5553 * @remarks
5554 * A `console` event provides a {@link ConsoleMessage} representing the
5555 * console message that was logged.
5556 *
5557 * @example
5558 * An example of handling `console` event:
5559 *
5560 * ```ts
5561 * page.on('console', msg => {
5562 * for (let i = 0; i < msg.args().length; ++i)
5563 * console.log(`${i}: ${msg.args()[i]}`);
5564 * });
5565 * page.evaluate(() => console.log('hello', 5, {foo: 'bar'}));
5566 * ```
5567 */
5568 Console = "console",
5569 /**
5570 * Emitted when a JavaScript dialog appears, such as `alert`, `prompt`,
5571 * `confirm` or `beforeunload`. Puppeteer can respond to the dialog via
5572 * {@link Dialog.accept} or {@link Dialog.dismiss}.
5573 */
5574 Dialog = "dialog",
5575 /**
5576 * Emitted when the JavaScript
5577 * {@link https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded | DOMContentLoaded }
5578 * event is dispatched.
5579 */
5580 DOMContentLoaded = "domcontentloaded",
5581 /**
5582 * Emitted when the page crashes. Will contain an `Error`.
5583 */
5584 Error = "error",
5585 /** Emitted when a frame is attached. Will contain a {@link Frame}. */
5586 FrameAttached = "frameattached",
5587 /** Emitted when a frame is detached. Will contain a {@link Frame}. */
5588 FrameDetached = "framedetached",
5589 /**
5590 * Emitted when a frame is navigated to a new URL. Will contain a
5591 * {@link Frame}.
5592 */
5593 FrameNavigated = "framenavigated",
5594 /**
5595 * Emitted when the JavaScript
5596 * {@link https://developer.mozilla.org/en-US/docs/Web/Events/load | load}
5597 * event is dispatched.
5598 */
5599 Load = "load",
5600 /**
5601 * Emitted when the JavaScript code makes a call to `console.timeStamp`. For
5602 * the list of metrics see {@link Page.metrics | page.metrics}.
5603 *
5604 * @remarks
5605 * Contains an object with two properties:
5606 *
5607 * - `title`: the title passed to `console.timeStamp`
5608 * - `metrics`: object containing metrics as key/value pairs. The values will
5609 * be `number`s.
5610 */
5611 Metrics = "metrics",
5612 /**
5613 * Emitted when an uncaught exception happens within the page. Contains an
5614 * `Error`.
5615 */
5616 PageError = "pageerror",
5617 /**
5618 * Emitted when the page opens a new tab or window.
5619 *
5620 * Contains a {@link Page} corresponding to the popup window.
5621 *
5622 * @example
5623 *
5624 * ```ts
5625 * const [popup] = await Promise.all([
5626 * new Promise(resolve => page.once('popup', resolve)),
5627 * page.click('a[target=_blank]'),
5628 * ]);
5629 * ```
5630 *
5631 * ```ts
5632 * const [popup] = await Promise.all([
5633 * new Promise(resolve => page.once('popup', resolve)),
5634 * page.evaluate(() => window.open('https://example.com')),
5635 * ]);
5636 * ```
5637 */
5638 Popup = "popup",
5639 /**
5640 * Emitted when a page issues a request and contains a {@link HTTPRequest}.
5641 *
5642 * @remarks
5643 * The object is readonly. See {@link Page.setRequestInterception} for
5644 * intercepting and mutating requests.
5645 */
5646 Request = "request",
5647 /**
5648 * Emitted when a request ended up loading from cache. Contains a
5649 * {@link HTTPRequest}.
5650 *
5651 * @remarks
5652 * For certain requests, might contain undefined.
5653 * {@link https://crbug.com/750469}
5654 */
5655 RequestServedFromCache = "requestservedfromcache",
5656 /**
5657 * Emitted when a request fails, for example by timing out.
5658 *
5659 * Contains a {@link HTTPRequest}.
5660 *
5661 * @remarks
5662 * HTTP Error responses, such as 404 or 503, are still successful responses
5663 * from HTTP standpoint, so request will complete with `requestfinished` event
5664 * and not with `requestfailed`.
5665 */
5666 RequestFailed = "requestfailed",
5667 /**
5668 * Emitted when a request finishes successfully. Contains a
5669 * {@link HTTPRequest}.
5670 */
5671 RequestFinished = "requestfinished",
5672 /**
5673 * Emitted when a response is received. Contains a {@link HTTPResponse}.
5674 */
5675 Response = "response",
5676 /**
5677 * Emitted when a dedicated
5678 * {@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API | WebWorker}
5679 * is spawned by the page.
5680 */
5681 WorkerCreated = "workercreated",
5682 /**
5683 * Emitted when a dedicated
5684 * {@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API | WebWorker}
5685 * is destroyed by the page.
5686 */
5687 WorkerDestroyed = "workerdestroyed"
5688 }
5689
5690 /**
5691 * Denotes the objects received by callback functions for page events.
5692 *
5693 * See {@link PageEmittedEvents} for more detail on the events and when they are
5694 * emitted.
5695 *
5696 * @public
5697 */
5698 export declare interface PageEventObject {
5699 close: never;
5700 console: ConsoleMessage;
5701 dialog: Dialog;
5702 domcontentloaded: never;
5703 error: Error;
5704 frameattached: Frame;
5705 framedetached: Frame;
5706 framenavigated: Frame;
5707 load: never;
5708 metrics: {
5709 title: string;
5710 metrics: Metrics;
5711 };
5712 pageerror: Error;
5713 popup: Page;
5714 request: HTTPRequest;
5715 response: HTTPResponse;
5716 requestfailed: HTTPRequest;
5717 requestfinished: HTTPRequest;
5718 requestservedfromcache: HTTPRequest;
5719 workercreated: WebWorker;
5720 workerdestroyed: WebWorker;
5721 }
5722
5723 /**
5724 * All the valid paper format types when printing a PDF.
5725 *
5726 * @remarks
5727 *
5728 * The sizes of each format are as follows:
5729 *
5730 * - `Letter`: 8.5in x 11in
5731 *
5732 * - `Legal`: 8.5in x 14in
5733 *
5734 * - `Tabloid`: 11in x 17in
5735 *
5736 * - `Ledger`: 17in x 11in
5737 *
5738 * - `A0`: 33.1in x 46.8in
5739 *
5740 * - `A1`: 23.4in x 33.1in
5741 *
5742 * - `A2`: 16.54in x 23.4in
5743 *
5744 * - `A3`: 11.7in x 16.54in
5745 *
5746 * - `A4`: 8.27in x 11.7in
5747 *
5748 * - `A5`: 5.83in x 8.27in
5749 *
5750 * - `A6`: 4.13in x 5.83in
5751 *
5752 * @public
5753 */
5754 export declare type PaperFormat = Uppercase<LowerCasePaperFormat> | Capitalize<LowerCasePaperFormat> | LowerCasePaperFormat;
5755
5756 /* Excluded from this release type: PaperFormatDimensions */
5757
5758 /* Excluded from this release type: _paperFormats */
5759
5760 /**
5761 * Copyright 2020 Google Inc. All rights reserved.
5762 *
5763 * Licensed under the Apache License, Version 2.0 (the "License");
5764 * you may not use this file except in compliance with the License.
5765 * You may obtain a copy of the License at
5766 *
5767 * http://www.apache.org/licenses/LICENSE-2.0
5768 *
5769 * Unless required by applicable law or agreed to in writing, software
5770 * distributed under the License is distributed on an "AS IS" BASIS,
5771 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5772 * See the License for the specific language governing permissions and
5773 * limitations under the License.
5774 */
5775 /**
5776 * @public
5777 */
5778 export declare interface PDFMargin {
5779 top?: string | number;
5780 bottom?: string | number;
5781 left?: string | number;
5782 right?: string | number;
5783 }
5784
5785 /**
5786 * Valid options to configure PDF generation via {@link Page.pdf}.
5787 * @public
5788 */
5789 export declare interface PDFOptions {
5790 /**
5791 * Scales the rendering of the web page. Amount must be between `0.1` and `2`.
5792 * @defaultValue 1
5793 */
5794 scale?: number;
5795 /**
5796 * Whether to show the header and footer.
5797 * @defaultValue false
5798 */
5799 displayHeaderFooter?: boolean;
5800 /**
5801 * HTML template for the print header. Should be valid HTML with the following
5802 * classes used to inject values into them:
5803 *
5804 * - `date` formatted print date
5805 *
5806 * - `title` document title
5807 *
5808 * - `url` document location
5809 *
5810 * - `pageNumber` current page number
5811 *
5812 * - `totalPages` total pages in the document
5813 */
5814 headerTemplate?: string;
5815 /**
5816 * HTML template for the print footer. Has the same constraints and support
5817 * for special classes as {@link PDFOptions.headerTemplate}.
5818 */
5819 footerTemplate?: string;
5820 /**
5821 * Set to `true` to print background graphics.
5822 * @defaultValue false
5823 */
5824 printBackground?: boolean;
5825 /**
5826 * Whether to print in landscape orientation.
5827 * @defaultValue = false
5828 */
5829 landscape?: boolean;
5830 /**
5831 * Paper ranges to print, e.g. `1-5, 8, 11-13`.
5832 * @defaultValue The empty string, which means all pages are printed.
5833 */
5834 pageRanges?: string;
5835 /**
5836 * @remarks
5837 * If set, this takes priority over the `width` and `height` options.
5838 * @defaultValue `letter`.
5839 */
5840 format?: PaperFormat;
5841 /**
5842 * Sets the width of paper. You can pass in a number or a string with a unit.
5843 */
5844 width?: string | number;
5845 /**
5846 * Sets the height of paper. You can pass in a number or a string with a unit.
5847 */
5848 height?: string | number;
5849 /**
5850 * Give any CSS `@page` size declared in the page priority over what is
5851 * declared in the `width` or `height` or `format` option.
5852 * @defaultValue `false`, which will scale the content to fit the paper size.
5853 */
5854 preferCSSPageSize?: boolean;
5855 /**
5856 * Set the PDF margins.
5857 * @defaultValue no margins are set.
5858 */
5859 margin?: PDFMargin;
5860 /**
5861 * The path to save the file to.
5862 *
5863 * @remarks
5864 *
5865 * If the path is relative, it's resolved relative to the current working directory.
5866 *
5867 * @defaultValue the empty string, which means the PDF will not be written to disk.
5868 */
5869 path?: string;
5870 /**
5871 * Hides default white background and allows generating pdfs with transparency.
5872 * @defaultValue false
5873 */
5874 omitBackground?: boolean;
5875 /**
5876 * Timeout in milliseconds. Pass `0` to disable timeout.
5877 * @defaultValue 30000
5878 */
5879 timeout?: number;
5880 }
5881
5882 /**
5883 * @public
5884 */
5885 export declare type Permission = 'geolocation' | 'midi' | 'notifications' | 'camera' | 'microphone' | 'background-sync' | 'ambient-light-sensor' | 'accelerometer' | 'gyroscope' | 'magnetometer' | 'accessibility-events' | 'clipboard-read' | 'clipboard-write' | 'payment-handler' | 'persistent-storage' | 'idle-detection' | 'midi-sysex';
5886
5887 /* Excluded from this release type: PipeTransport */
5888
5889 /**
5890 * Supported platforms.
5891 *
5892 * @public
5893 */
5894 export declare type Platform = 'linux' | 'mac' | 'mac_arm' | 'win32' | 'win64';
5895
5896 /**
5897 * @public
5898 */
5899 export declare interface Point {
5900 x: number;
5901 y: number;
5902 }
5903
5904 /* Excluded from this release type: Poller */
5905
5906 /**
5907 * A list of network conditions to be used with
5908 * {@link Page.emulateNetworkConditions}.
5909 *
5910 * @example
5911 *
5912 * ```ts
5913 * import {PredefinedNetworkConditions} from 'puppeteer';
5914 * const slow3G = PredefinedNetworkConditions['Slow 3G'];
5915 *
5916 * (async () => {
5917 * const browser = await puppeteer.launch();
5918 * const page = await browser.newPage();
5919 * await page.emulateNetworkConditions(slow3G);
5920 * await page.goto('https://www.google.com');
5921 * // other actions...
5922 * await browser.close();
5923 * })();
5924 * ```
5925 *
5926 * @public
5927 */
5928 export declare const PredefinedNetworkConditions: Readonly<{
5929 'Slow 3G': NetworkConditions;
5930 'Fast 3G': NetworkConditions;
5931 }>;
5932
5933 /**
5934 * @public
5935 */
5936 export declare interface PressOptions {
5937 /**
5938 * Time to wait between `keydown` and `keyup` in milliseconds. Defaults to 0.
5939 */
5940 delay?: number;
5941 /**
5942 * If specified, generates an input event with this text.
5943 */
5944 text?: string;
5945 }
5946
5947 /**
5948 * Copyright 2020 Google Inc. All rights reserved.
5949 *
5950 * Licensed under the Apache License, Version 2.0 (the "License");
5951 * you may not use this file except in compliance with the License.
5952 * You may obtain a copy of the License at
5953 *
5954 * http://www.apache.org/licenses/LICENSE-2.0
5955 *
5956 * Unless required by applicable law or agreed to in writing, software
5957 * distributed under the License is distributed on an "AS IS" BASIS,
5958 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5959 * See the License for the specific language governing permissions and
5960 * limitations under the License.
5961 */
5962 /**
5963 * Supported products.
5964 * @public
5965 */
5966 export declare type Product = 'chrome' | 'firefox';
5967
5968 /**
5969 * Describes a launcher - a class that is able to create and launch a browser instance.
5970 *
5971 * @public
5972 */
5973 export declare class ProductLauncher {
5974 #private;
5975 /* Excluded from this release type: puppeteer */
5976 /* Excluded from this release type: actualBrowserRevision */
5977 /* Excluded from this release type: __constructor */
5978 get product(): Product;
5979 launch(object: PuppeteerNodeLaunchOptions): Promise<Browser>;
5980 executablePath(channel?: ChromeReleaseChannel): string;
5981 defaultArgs(object: BrowserLaunchArgumentOptions): string[];
5982 /* Excluded from this release type: getActualBrowserRevision */
5983 /* Excluded from this release type: getProfilePath */
5984 /* Excluded from this release type: resolveExecutablePath */
5985 }
5986
5987 export { Protocol }
5988
5989 /**
5990 * ProtocolError is emitted whenever there is an error from the protocol.
5991 *
5992 * @public
5993 */
5994 export declare class ProtocolError extends CustomError {
5995 #private;
5996 /**
5997 * @internal
5998 */
5999 set code(code: number | undefined);
6000 /**
6001 * @public
6002 */
6003 get code(): number | undefined;
6004 /**
6005 * @internal
6006 */
6007 set originalMessage(originalMessage: string);
6008 /**
6009 * @public
6010 */
6011 get originalMessage(): string;
6012 }
6013
6014 /**
6015 * @public
6016 */
6017 export declare type ProtocolLifeCycleEvent = 'load' | 'DOMContentLoaded' | 'networkIdle' | 'networkAlmostIdle';
6018
6019 export { ProtocolMapping }
6020
6021 /**
6022 * The main Puppeteer class.
6023 *
6024 * IMPORTANT: if you are using Puppeteer in a Node environment, you will get an
6025 * instance of {@link PuppeteerNode} when you import or require `puppeteer`.
6026 * That class extends `Puppeteer`, so has all the methods documented below as
6027 * well as all that are defined on {@link PuppeteerNode}.
6028 * @public
6029 */
6030 export declare class Puppeteer {
6031 /**
6032 * Registers a {@link CustomQueryHandler | custom query handler}.
6033 *
6034 * @remarks
6035 * After registration, the handler can be used everywhere where a selector is
6036 * expected by prepending the selection string with `<name>/`. The name is only
6037 * allowed to consist of lower- and upper case latin letters.
6038 *
6039 * @example
6040 *
6041 * ```
6042 * puppeteer.registerCustomQueryHandler('text', { … });
6043 * const aHandle = await page.$('text/…');
6044 * ```
6045 *
6046 * @param name - The name that the custom query handler will be registered
6047 * under.
6048 * @param queryHandler - The {@link CustomQueryHandler | custom query handler}
6049 * to register.
6050 *
6051 * @public
6052 */
6053 static registerCustomQueryHandler(name: string, queryHandler: CustomQueryHandler): void;
6054 /**
6055 * Unregisters a custom query handler for a given name.
6056 */
6057 static unregisterCustomQueryHandler(name: string): void;
6058 /**
6059 * Gets the names of all custom query handlers.
6060 */
6061 static customQueryHandlerNames(): string[];
6062 /**
6063 * Unregisters all custom query handlers.
6064 */
6065 static clearCustomQueryHandlers(): void;
6066 /* Excluded from this release type: _isPuppeteerCore */
6067 /* Excluded from this release type: _changedProduct */
6068 /* Excluded from this release type: __constructor */
6069 /**
6070 * This method attaches Puppeteer to an existing browser instance.
6071 *
6072 * @remarks
6073 *
6074 * @param options - Set of configurable options to set on the browser.
6075 * @returns Promise which resolves to browser instance.
6076 */
6077 connect(options: ConnectOptions): Promise<Browser>;
6078 }
6079
6080 /**
6081 * @public
6082 */
6083 declare const puppeteer: PuppeteerNode;
6084 export default puppeteer;
6085
6086 /* Excluded from this release type: PUPPETEER_REVISIONS */
6087
6088 /* Excluded from this release type: PUPPETEER_WORLD */
6089
6090 /**
6091 * @deprecated Do not use.
6092 *
6093 * @public
6094 */
6095 export declare interface PuppeteerErrors {
6096 TimeoutError: typeof TimeoutError;
6097 ProtocolError: typeof ProtocolError;
6098 }
6099
6100 /* Excluded from this release type: PuppeteerEventListener */
6101
6102 /**
6103 * @public
6104 */
6105 export declare interface PuppeteerLaunchOptions extends LaunchOptions, BrowserLaunchArgumentOptions, BrowserConnectOptions {
6106 product?: Product;
6107 extraPrefsFirefox?: Record<string, unknown>;
6108 }
6109
6110 /**
6111 * @public
6112 */
6113 export declare type PuppeteerLifeCycleEvent = 'load' | 'domcontentloaded' | 'networkidle0' | 'networkidle2';
6114
6115 /**
6116 * Extends the main {@link Puppeteer} class with Node specific behaviour for
6117 * fetching and downloading browsers.
6118 *
6119 * If you're using Puppeteer in a Node environment, this is the class you'll get
6120 * when you run `require('puppeteer')` (or the equivalent ES `import`).
6121 *
6122 * @remarks
6123 * The most common method to use is {@link PuppeteerNode.launch | launch}, which
6124 * is used to launch and connect to a new browser instance.
6125 *
6126 * See {@link Puppeteer | the main Puppeteer class} for methods common to all
6127 * environments, such as {@link Puppeteer.connect}.
6128 *
6129 * @example
6130 * The following is a typical example of using Puppeteer to drive automation:
6131 *
6132 * ```ts
6133 * import puppeteer from 'puppeteer';
6134 *
6135 * (async () => {
6136 * const browser = await puppeteer.launch();
6137 * const page = await browser.newPage();
6138 * await page.goto('https://www.google.com');
6139 * // other actions...
6140 * await browser.close();
6141 * })();
6142 * ```
6143 *
6144 * Once you have created a `page` you have access to a large API to interact
6145 * with the page, navigate, or find certain elements in that page.
6146 * The {@link Page | `page` documentation} lists all the available methods.
6147 *
6148 * @public
6149 */
6150 export declare class PuppeteerNode extends Puppeteer {
6151 #private;
6152 /* Excluded from this release type: defaultBrowserRevision */
6153 /* Excluded from this release type: configuration */
6154 /* Excluded from this release type: __constructor */
6155 /**
6156 * This method attaches Puppeteer to an existing browser instance.
6157 *
6158 * @param options - Set of configurable options to set on the browser.
6159 * @returns Promise which resolves to browser instance.
6160 *
6161 * @public
6162 */
6163 connect(options: ConnectOptions): Promise<Browser>;
6164 /**
6165 * Launches a browser instance with given arguments and options when
6166 * specified.
6167 *
6168 * When using with `puppeteer-core`,
6169 * {@link LaunchOptions.executablePath | options.executablePath} or
6170 * {@link LaunchOptions.channel | options.channel} must be provided.
6171 *
6172 * @example
6173 * You can use {@link LaunchOptions.ignoreDefaultArgs | options.ignoreDefaultArgs}
6174 * to filter out `--mute-audio` from default arguments:
6175 *
6176 * ```ts
6177 * const browser = await puppeteer.launch({
6178 * ignoreDefaultArgs: ['--mute-audio'],
6179 * });
6180 * ```
6181 *
6182 * @remarks
6183 * Puppeteer can also be used to control the Chrome browser, but it works best
6184 * with the version of Chromium downloaded by default by Puppeteer. There is
6185 * no guarantee it will work with any other version. If Google Chrome (rather
6186 * than Chromium) is preferred, a
6187 * {@link https://www.google.com/chrome/browser/canary.html | Chrome Canary}
6188 * or
6189 * {@link https://www.chromium.org/getting-involved/dev-channel | Dev Channel}
6190 * build is suggested. See
6191 * {@link https://www.howtogeek.com/202825/what%E2%80%99s-the-difference-between-chromium-and-chrome/ | this article}
6192 * for a description of the differences between Chromium and Chrome.
6193 * {@link https://chromium.googlesource.com/chromium/src/+/lkgr/docs/chromium_browser_vs_google_chrome.md | This article}
6194 * describes some differences for Linux users.
6195 *
6196 * @param options - Options to configure launching behavior.
6197 *
6198 * @public
6199 */
6200 launch(options?: PuppeteerLaunchOptions): Promise<Browser>;
6201 /**
6202 * @returns The default executable path.
6203 *
6204 * @public
6205 */
6206 executablePath(channel?: ChromeReleaseChannel): string;
6207 /* Excluded from this release type: browserRevision */
6208 /* Excluded from this release type: defaultDownloadPath */
6209 /**
6210 * @returns The name of the browser that was last launched.
6211 *
6212 * @public
6213 */
6214 get lastLaunchedProduct(): Product;
6215 /**
6216 * @returns The name of the browser that will be launched by default. For
6217 * `puppeteer`, this is influenced by your configuration. Otherwise, it's
6218 * `chrome`.
6219 *
6220 * @public
6221 */
6222 get defaultProduct(): Product;
6223 /**
6224 * @deprecated Do not use as this field as it does not take into account
6225 * multiple browsers of different types. Use
6226 * {@link PuppeteerNode.defaultProduct | defaultProduct} or
6227 * {@link PuppeteerNode.lastLaunchedProduct | lastLaunchedProduct}.
6228 *
6229 * @returns The name of the browser that is under automation.
6230 *
6231 * @public
6232 */
6233 get product(): string;
6234 /**
6235 * @param options - Set of configurable options to set on the browser.
6236 *
6237 * @returns The default flags that Chromium will be launched with.
6238 *
6239 * @public
6240 */
6241 defaultArgs(options?: BrowserLaunchArgumentOptions): string[];
6242 /**
6243 * @param options - Set of configurable options to specify the settings of the
6244 * BrowserFetcher.
6245 *
6246 * @remarks
6247 * If you are using `puppeteer-core`, do not use this method. Just
6248 * construct {@link BrowserFetcher} manually.
6249 *
6250 * @returns A new BrowserFetcher instance.
6251 */
6252 createBrowserFetcher(options?: Partial<BrowserFetcherOptions>): BrowserFetcher;
6253 }
6254
6255 /**
6256 * Utility type exposed to enable users to define options that can be passed to
6257 * `puppeteer.launch` without having to list the set of all types.
6258 * @public
6259 */
6260 export declare type PuppeteerNodeLaunchOptions = BrowserLaunchArgumentOptions & LaunchOptions & BrowserConnectOptions;
6261
6262 /* Excluded from this release type: PuppeteerQueryHandler */
6263
6264 /* Excluded from this release type: PuppeteerUtil */
6265
6266 /* Excluded from this release type: QueuedEventGroup */
6267
6268 /* Excluded from this release type: RAFPoller */
6269
6270 /* Excluded from this release type: RedirectInfo */
6271
6272 /**
6273 * @deprecated Import {@link Puppeteer} and use the static method
6274 * {@link Puppeteer.registerCustomQueryHandler}
6275 *
6276 * @public
6277 */
6278 export declare function registerCustomQueryHandler(name: string, handler: CustomQueryHandler): void;
6279
6280 /* Excluded from this release type: releaseObject */
6281
6282 /**
6283 * @public
6284 */
6285 export declare interface RemoteAddress {
6286 ip?: string;
6287 port?: number;
6288 }
6289
6290 /* Excluded from this release type: removeEventListeners */
6291
6292 /**
6293 * Resource types for HTTPRequests as perceived by the rendering engine.
6294 *
6295 * @public
6296 */
6297 export declare type ResourceType = Lowercase<Protocol.Network.ResourceType>;
6298
6299 /**
6300 * Required response data to fulfill a request with.
6301 *
6302 * @public
6303 */
6304 export declare interface ResponseForRequest {
6305 status: number;
6306 /**
6307 * Optional response headers. All values are converted to strings.
6308 */
6309 headers: Record<string, unknown>;
6310 contentType: string;
6311 body: string | Buffer;
6312 }
6313
6314 /**
6315 * @public
6316 */
6317 export declare interface ScreenshotClip {
6318 x: number;
6319 y: number;
6320 width: number;
6321 height: number;
6322 /**
6323 * @defaultValue 1
6324 */
6325 scale?: number;
6326 }
6327
6328 /**
6329 * @public
6330 */
6331 export declare interface ScreenshotOptions {
6332 /**
6333 * @defaultValue `png`
6334 */
6335 type?: 'png' | 'jpeg' | 'webp';
6336 /**
6337 * The file path to save the image to. The screenshot type will be inferred
6338 * from file extension. If path is a relative path, then it is resolved
6339 * relative to current working directory. If no path is provided, the image
6340 * won't be saved to the disk.
6341 */
6342 path?: string;
6343 /**
6344 * When `true`, takes a screenshot of the full page.
6345 * @defaultValue `false`
6346 */
6347 fullPage?: boolean;
6348 /**
6349 * An object which specifies the clipping region of the page.
6350 */
6351 clip?: ScreenshotClip;
6352 /**
6353 * Quality of the image, between 0-100. Not applicable to `png` images.
6354 */
6355 quality?: number;
6356 /**
6357 * Hides default white background and allows capturing screenshots with transparency.
6358 * @defaultValue `false`
6359 */
6360 omitBackground?: boolean;
6361 /**
6362 * Encoding of the image.
6363 * @defaultValue `binary`
6364 */
6365 encoding?: 'base64' | 'binary';
6366 /**
6367 * Capture the screenshot beyond the viewport.
6368 * @defaultValue `true`
6369 */
6370 captureBeyondViewport?: boolean;
6371 /**
6372 * Capture the screenshot from the surface, rather than the view.
6373 * @defaultValue `true`
6374 */
6375 fromSurface?: boolean;
6376 }
6377
6378 /**
6379 * The SecurityDetails class represents the security details of a
6380 * response that was received over a secure connection.
6381 *
6382 * @public
6383 */
6384 export declare class SecurityDetails {
6385 #private;
6386 /* Excluded from this release type: __constructor */
6387 /**
6388 * @returns The name of the issuer of the certificate.
6389 */
6390 issuer(): string;
6391 /**
6392 * @returns {@link https://en.wikipedia.org/wiki/Unix_time | Unix timestamp}
6393 * marking the start of the certificate's validity.
6394 */
6395 validFrom(): number;
6396 /**
6397 * @returns {@link https://en.wikipedia.org/wiki/Unix_time | Unix timestamp}
6398 * marking the end of the certificate's validity.
6399 */
6400 validTo(): number;
6401 /**
6402 * @returns The security protocol being used, e.g. "TLS 1.2".
6403 */
6404 protocol(): string;
6405 /**
6406 * @returns The name of the subject to which the certificate was issued.
6407 */
6408 subjectName(): string;
6409 /**
6410 * @returns The list of {@link https://en.wikipedia.org/wiki/Subject_Alternative_Name | subject alternative names (SANs)} of the certificate.
6411 */
6412 subjectAlternativeNames(): string[];
6413 }
6414
6415 /**
6416 * Represents a Node and the properties of it that are relevant to Accessibility.
6417 * @public
6418 */
6419 export declare interface SerializedAXNode {
6420 /**
6421 * The {@link https://www.w3.org/TR/wai-aria/#usage_intro | role} of the node.
6422 */
6423 role: string;
6424 /**
6425 * A human readable name for the node.
6426 */
6427 name?: string;
6428 /**
6429 * The current value of the node.
6430 */
6431 value?: string | number;
6432 /**
6433 * An additional human readable description of the node.
6434 */
6435 description?: string;
6436 /**
6437 * Any keyboard shortcuts associated with this node.
6438 */
6439 keyshortcuts?: string;
6440 /**
6441 * A human readable alternative to the role.
6442 */
6443 roledescription?: string;
6444 /**
6445 * A description of the current value.
6446 */
6447 valuetext?: string;
6448 disabled?: boolean;
6449 expanded?: boolean;
6450 focused?: boolean;
6451 modal?: boolean;
6452 multiline?: boolean;
6453 /**
6454 * Whether more than one child can be selected.
6455 */
6456 multiselectable?: boolean;
6457 readonly?: boolean;
6458 required?: boolean;
6459 selected?: boolean;
6460 /**
6461 * Whether the checkbox is checked, or in a
6462 * {@link https://www.w3.org/TR/wai-aria-practices/examples/checkbox/checkbox-2/checkbox-2.html | mixed state}.
6463 */
6464 checked?: boolean | 'mixed';
6465 /**
6466 * Whether the node is checked or in a mixed state.
6467 */
6468 pressed?: boolean | 'mixed';
6469 /**
6470 * The level of a heading.
6471 */
6472 level?: number;
6473 valuemin?: number;
6474 valuemax?: number;
6475 autocomplete?: string;
6476 haspopup?: string;
6477 /**
6478 * Whether and in what way this node's value is invalid.
6479 */
6480 invalid?: string;
6481 orientation?: string;
6482 /**
6483 * Children of this node, if there are any.
6484 */
6485 children?: SerializedAXNode[];
6486 }
6487
6488 /* Excluded from this release type: setLogCapture */
6489
6490 /**
6491 * @public
6492 */
6493 export declare interface SnapshotOptions {
6494 /**
6495 * Prune uninteresting nodes from the tree.
6496 * @defaultValue true
6497 */
6498 interestingOnly?: boolean;
6499 /**
6500 * Root node to get the accessibility tree for
6501 * @defaultValue The root node of the entire page.
6502 */
6503 root?: ElementHandle<Node>;
6504 }
6505
6506 declare type Split<Input extends string, Delimiter extends string, Acc extends string[] = []> = Input extends `${infer Prefix}${Delimiter}${infer Suffix}` ? Split<Suffix, Delimiter, [...Acc, Prefix]> : [...Acc, Input];
6507
6508 declare type SplitWithDelemiters<Input extends string, Delemiters extends readonly string[]> = Delemiters extends [infer FirstDelemiter, ...infer RestDelemiters] ? FirstDelemiter extends string ? RestDelemiters extends readonly string[] ? FlatmapSplitWithDelemiters<Split<Input, FirstDelemiter>, RestDelemiters> : never : never : [Input];
6509
6510 /* Excluded from this release type: supportedMetrics */
6511
6512 /**
6513 * Target represents a
6514 * {@link https://chromedevtools.github.io/devtools-protocol/tot/Target/ | CDP target}.
6515 * In CDP a target is something that can be debugged such a frame, a page or a
6516 * worker.
6517 *
6518 * @public
6519 */
6520 export declare class Target {
6521 #private;
6522 /* Excluded from this release type: _initializedPromise */
6523 /* Excluded from this release type: _initializedCallback */
6524 /* Excluded from this release type: _isClosedPromise */
6525 /* Excluded from this release type: _closedCallback */
6526 /* Excluded from this release type: _isInitialized */
6527 /* Excluded from this release type: _targetId */
6528 /* Excluded from this release type: _isPageTargetCallback */
6529 /* Excluded from this release type: __constructor */
6530 /* Excluded from this release type: _session */
6531 /**
6532 * Creates a Chrome Devtools Protocol session attached to the target.
6533 */
6534 createCDPSession(): Promise<CDPSession>;
6535 /* Excluded from this release type: _targetManager */
6536 /* Excluded from this release type: _getTargetInfo */
6537 /**
6538 * If the target is not of type `"page"` or `"background_page"`, returns `null`.
6539 */
6540 page(): Promise<Page | null>;
6541 /**
6542 * If the target is not of type `"service_worker"` or `"shared_worker"`, returns `null`.
6543 */
6544 worker(): Promise<WebWorker | null>;
6545 url(): string;
6546 /**
6547 * Identifies what kind of target this is.
6548 *
6549 * @remarks
6550 *
6551 * See {@link https://developer.chrome.com/extensions/background_pages | docs} for more info about background pages.
6552 */
6553 type(): 'page' | 'background_page' | 'service_worker' | 'shared_worker' | 'other' | 'browser' | 'webview';
6554 /**
6555 * Get the browser the target belongs to.
6556 */
6557 browser(): Browser;
6558 /**
6559 * Get the browser context the target belongs to.
6560 */
6561 browserContext(): BrowserContext;
6562 /**
6563 * Get the target that opened this target. Top-level targets return `null`.
6564 */
6565 opener(): Target | undefined;
6566 /* Excluded from this release type: _targetInfoChanged */
6567 }
6568
6569 /* Excluded from this release type: TargetFactory */
6570
6571 /**
6572 * @public
6573 */
6574 export declare type TargetFilterCallback = (target: Protocol.Target.TargetInfo) => boolean;
6575
6576 /* Excluded from this release type: TargetInterceptor */
6577
6578 /* Excluded from this release type: TargetManager */
6579
6580 /* Excluded from this release type: TargetManagerEmittedEvents */
6581
6582 /* Excluded from this release type: TaskManager */
6583
6584 /* Excluded from this release type: TaskQueue */
6585
6586 /* Excluded from this release type: TextContent */
6587
6588 /**
6589 * TimeoutError is emitted whenever certain operations are terminated due to
6590 * timeout.
6591 *
6592 * @remarks
6593 * Example operations are {@link Page.waitForSelector | page.waitForSelector} or
6594 * {@link PuppeteerNode.launch | puppeteer.launch}.
6595 *
6596 * @public
6597 */
6598 export declare class TimeoutError extends CustomError {
6599 }
6600
6601 /* Excluded from this release type: TimeoutSettings */
6602
6603 /**
6604 * The Touchscreen class exposes touchscreen events.
6605 * @public
6606 */
6607 export declare class Touchscreen {
6608 #private;
6609 /* Excluded from this release type: __constructor */
6610 /**
6611 * Dispatches a `touchstart` and `touchend` event.
6612 * @param x - Horizontal position of the tap.
6613 * @param y - Vertical position of the tap.
6614 */
6615 tap(x: number, y: number): Promise<void>;
6616 }
6617
6618 /**
6619 * The Tracing class exposes the tracing audit interface.
6620 * @remarks
6621 * You can use `tracing.start` and `tracing.stop` to create a trace file
6622 * which can be opened in Chrome DevTools or {@link https://chromedevtools.github.io/timeline-viewer/ | timeline viewer}.
6623 *
6624 * @example
6625 *
6626 * ```ts
6627 * await page.tracing.start({path: 'trace.json'});
6628 * await page.goto('https://www.google.com');
6629 * await page.tracing.stop();
6630 * ```
6631 *
6632 * @public
6633 */
6634 export declare class Tracing {
6635 #private;
6636 /* Excluded from this release type: __constructor */
6637 /**
6638 * Starts a trace for the current page.
6639 * @remarks
6640 * Only one trace can be active at a time per browser.
6641 *
6642 * @param options - Optional `TracingOptions`.
6643 */
6644 start(options?: TracingOptions): Promise<void>;
6645 /**
6646 * Stops a trace started with the `start` method.
6647 * @returns Promise which resolves to buffer with trace data.
6648 */
6649 stop(): Promise<Buffer | undefined>;
6650 }
6651
6652 /**
6653 * @public
6654 */
6655 export declare interface TracingOptions {
6656 path?: string;
6657 screenshots?: boolean;
6658 categories?: string[];
6659 }
6660
6661 declare type TypeSelectorOfComplexSelector<ComplexSelector extends string> = CompoundSelectorsOfComplexSelector<ComplexSelector> extends infer CompoundSelectors ? CompoundSelectors extends NonEmptyReadonlyArray<string> ? Last<CompoundSelectors> extends infer LastCompoundSelector ? LastCompoundSelector extends string ? TypeSelectorOfCompoundSelector<LastCompoundSelector> : never : never : unknown : never;
6662
6663 declare type TypeSelectorOfCompoundSelector<CompoundSelector extends string> = SplitWithDelemiters<CompoundSelector, BeginSubclassSelectorTokens> extends infer CompoundSelectorTokens ? CompoundSelectorTokens extends [infer TypeSelector, ...any[]] ? TypeSelector extends '' ? unknown : TypeSelector : never : never;
6664
6665 /* Excluded from this release type: unitToPixels */
6666
6667 /**
6668 * @deprecated Import {@link Puppeteer} and use the static method
6669 * {@link Puppeteer.unregisterCustomQueryHandler}
6670 *
6671 * @public
6672 */
6673 export declare function unregisterCustomQueryHandler(name: string): void;
6674
6675 /* Excluded from this release type: valueFromRemoteObject */
6676
6677 /**
6678 * Copyright 2020 Google Inc. All rights reserved.
6679 *
6680 * Licensed under the Apache License, Version 2.0 (the "License");
6681 * you may not use this file except in compliance with the License.
6682 * You may obtain a copy of the License at
6683 *
6684 * http://www.apache.org/licenses/LICENSE-2.0
6685 *
6686 * Unless required by applicable law or agreed to in writing, software
6687 * distributed under the License is distributed on an "AS IS" BASIS,
6688 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6689 * See the License for the specific language governing permissions and
6690 * limitations under the License.
6691 */
6692 /**
6693 *
6694 * Sets the viewport of the page.
6695 * @public
6696 */
6697 export declare interface Viewport {
6698 /**
6699 * The page width in pixels.
6700 */
6701 width: number;
6702 /**
6703 * The page height in pixels.
6704 */
6705 height: number;
6706 /**
6707 * Specify device scale factor.
6708 * See {@link https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio | devicePixelRatio} for more info.
6709 * @defaultValue 1
6710 */
6711 deviceScaleFactor?: number;
6712 /**
6713 * Whether the `meta viewport` tag is taken into account.
6714 * @defaultValue false
6715 */
6716 isMobile?: boolean;
6717 /**
6718 * Specifies if the viewport is in landscape mode.
6719 * @defaultValue false
6720 */
6721 isLandscape?: boolean;
6722 /**
6723 * Specify if the viewport supports touch events.
6724 * @defaultValue false
6725 */
6726 hasTouch?: boolean;
6727 }
6728
6729 /* Excluded from this release type: waitForEvent */
6730
6731 /**
6732 * @public
6733 */
6734 export declare interface WaitForOptions {
6735 /**
6736 * Maximum wait time in milliseconds. Pass 0 to disable the timeout.
6737 *
6738 * The default value can be changed by using the
6739 * {@link Page.setDefaultTimeout} or {@link Page.setDefaultNavigationTimeout}
6740 * methods.
6741 *
6742 * @defaultValue `30000`
6743 */
6744 timeout?: number;
6745 waitUntil?: PuppeteerLifeCycleEvent | PuppeteerLifeCycleEvent[];
6746 }
6747
6748 /**
6749 * @public
6750 */
6751 export declare interface WaitForSelectorOptions {
6752 /**
6753 * Wait for the selected element to be present in DOM and to be visible, i.e.
6754 * to not have `display: none` or `visibility: hidden` CSS properties.
6755 *
6756 * @defaultValue `false`
6757 */
6758 visible?: boolean;
6759 /**
6760 * Wait for the selected element to not be found in the DOM or to be hidden,
6761 * i.e. have `display: none` or `visibility: hidden` CSS properties.
6762 *
6763 * @defaultValue `false`
6764 */
6765 hidden?: boolean;
6766 /**
6767 * Maximum time to wait in milliseconds. Pass `0` to disable timeout.
6768 *
6769 * The default value can be changed by using {@link Page.setDefaultTimeout}
6770 *
6771 * @defaultValue `30000` (30 seconds)
6772 */
6773 timeout?: number;
6774 }
6775
6776 /**
6777 * @public
6778 */
6779 export declare interface WaitForTargetOptions {
6780 /**
6781 * Maximum wait time in milliseconds. Pass `0` to disable the timeout.
6782 * @defaultValue 30 seconds.
6783 */
6784 timeout?: number;
6785 }
6786
6787 /* Excluded from this release type: WaitTask */
6788
6789 /* Excluded from this release type: WaitTaskOptions */
6790
6791 /**
6792 * @public
6793 */
6794 export declare interface WaitTimeoutOptions {
6795 /**
6796 * Maximum wait time in milliseconds. Pass 0 to disable the timeout.
6797 *
6798 * The default value can be changed by using the
6799 * {@link Page.setDefaultTimeout} method.
6800 *
6801 * @defaultValue `30000`
6802 */
6803 timeout?: number;
6804 }
6805
6806 /* Excluded from this release type: waitWithTimeout */
6807
6808 /* Excluded from this release type: WEB_PERMISSION_TO_PROTOCOL_PERMISSION */
6809
6810 /**
6811 * This class represents a
6812 * {@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API | WebWorker}.
6813 *
6814 * @remarks
6815 * The events `workercreated` and `workerdestroyed` are emitted on the page
6816 * object to signal the worker lifecycle.
6817 *
6818 * @example
6819 *
6820 * ```ts
6821 * page.on('workercreated', worker =>
6822 * console.log('Worker created: ' + worker.url())
6823 * );
6824 * page.on('workerdestroyed', worker =>
6825 * console.log('Worker destroyed: ' + worker.url())
6826 * );
6827 *
6828 * console.log('Current workers:');
6829 * for (const worker of page.workers()) {
6830 * console.log(' ' + worker.url());
6831 * }
6832 * ```
6833 *
6834 * @public
6835 */
6836 export declare class WebWorker extends EventEmitter {
6837 #private;
6838 /* Excluded from this release type: __constructor */
6839 /* Excluded from this release type: executionContext */
6840 /**
6841 * @returns The URL of this web worker.
6842 */
6843 url(): string;
6844 /**
6845 * If the function passed to the `worker.evaluate` returns a Promise, then
6846 * `worker.evaluate` would wait for the promise to resolve and return its
6847 * value. If the function passed to the `worker.evaluate` returns a
6848 * non-serializable value, then `worker.evaluate` resolves to `undefined`.
6849 * DevTools Protocol also supports transferring some additional values that
6850 * are not serializable by `JSON`: `-0`, `NaN`, `Infinity`, `-Infinity`, and
6851 * bigint literals.
6852 * Shortcut for `await worker.executionContext()).evaluate(pageFunction, ...args)`.
6853 *
6854 * @param pageFunction - Function to be evaluated in the worker context.
6855 * @param args - Arguments to pass to `pageFunction`.
6856 * @returns Promise which resolves to the return value of `pageFunction`.
6857 */
6858 evaluate<Params extends unknown[], Func extends EvaluateFunc<Params> = EvaluateFunc<Params>>(pageFunction: Func | string, ...args: Params): Promise<Awaited<ReturnType<Func>>>;
6859 /**
6860 * The only difference between `worker.evaluate` and `worker.evaluateHandle`
6861 * is that `worker.evaluateHandle` returns in-page object (JSHandle). If the
6862 * function passed to the `worker.evaluateHandle` returns a `Promise`, then
6863 * `worker.evaluateHandle` would wait for the promise to resolve and return
6864 * its value. Shortcut for
6865 * `await worker.executionContext()).evaluateHandle(pageFunction, ...args)`
6866 *
6867 * @param pageFunction - Function to be evaluated in the page context.
6868 * @param args - Arguments to pass to `pageFunction`.
6869 * @returns Promise which resolves to the return value of `pageFunction`.
6870 */
6871 evaluateHandle<Params extends unknown[], Func extends EvaluateFunc<Params> = EvaluateFunc<Params>>(pageFunction: Func | string, ...args: Params): Promise<HandleFor<Awaited<ReturnType<Func>>>>;
6872 }
6873
6874 export { }
6875
\No newline at end of file