UNPKG

83.8 kBTypeScriptView Raw
1// Type definitions for puppeteer 5.4
2// Project: https://github.com/GoogleChrome/puppeteer#readme
3// Definitions by: Marvin Hagemeister <https://github.com/marvinhagemeister>
4// Christopher Deutsch <https://github.com/cdeutsch>
5// Konstantin Simon Maria Möllers <https://github.com/ksm2>
6// Simon Schick <https://github.com/SimonSchick>
7// Serban Ghita <https://github.com/SerbanGhita>
8// Jason Kaczmarsky <https://github.com/JasonKaz>
9// Dave Cardwell <https://github.com/davecardwell>
10// Andrés Ortiz <https://github.com/angrykoala>
11// Piotr Błażejewicz <https://github.com/peterblazejewicz>
12// Cameron Hunter <https://github.com/cameronhunter>
13// Pirasis Leelatanon <https://github.com/1pete>
14// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
15// TypeScript Version: 3.0
16
17/// <reference types="node" />
18
19import { ChildProcess } from 'child_process';
20
21export namespace devices {
22 interface Device {
23 name: string;
24 userAgent: string;
25 viewport: {
26 width: number;
27 height: number;
28 deviceScaleFactor: number;
29 isMobile: boolean;
30 hasTouch: boolean;
31 isLandscape: boolean;
32 };
33 }
34}
35
36export const devices: { [name: string]: devices.Device };
37
38declare class CustomError extends Error {
39 constructor(message: string);
40}
41
42/**
43 * TimeoutError is emitted whenever certain operations are terminated due to timeout.
44 *
45 * Example operations are {@link Page.waitForSelector | page.waitForSelector}
46 * or {@link PuppeteerNode.launch | puppeteer.launch}.
47 */
48declare class TimeoutError extends CustomError {}
49
50export namespace errors {
51 class TimeoutError extends CustomError {}
52}
53
54/** Wraps a DOM element into an ElementHandle instance */
55export type WrapElementHandle<X> = X extends Element ? ElementHandle<X> : X;
56
57/** Unwraps a DOM element out of an ElementHandle instance */
58export type UnwrapElementHandle<X> = X extends ElementHandle<infer E> ? E : X;
59
60export type Serializable = number | string | boolean | null | JSONArray | JSONObject;
61export interface JSONArray extends Array<Serializable> {}
62export interface JSONObject {
63 [key: string]: Serializable;
64}
65export type SerializableOrJSHandle = Serializable | JSHandle;
66
67export type Platform = 'mac' | 'win32' | 'win64' | 'linux';
68
69export type Product = 'chrome' | 'firefox';
70
71/** Defines `$eval` and `$$eval` for Page, Frame and ElementHandle. */
72export interface Evalable {
73 /**
74 * This method runs `document.querySelector` within the context and passes it as the first argument to `pageFunction`.
75 * If there's no element matching `selector`, the method throws an error.
76 *
77 * If `pageFunction` returns a Promise, then `$eval` would wait for the promise to resolve and return its value.
78 *
79 * @param selector A selector to query for
80 * @param pageFunction Function to be evaluated in browser context
81 * @returns Promise which resolves to the return value of pageFunction
82 */
83 $eval<R>(selector: string, pageFunction: (element: Element) => R | Promise<R>): Promise<WrapElementHandle<R>>;
84
85 /**
86 * This method runs `document.querySelector` within the context and passes it as the first argument to `pageFunction`.
87 * If there's no element matching `selector`, the method throws an error.
88 *
89 * If `pageFunction` returns a Promise, then `$eval` would wait for the promise to resolve and return its value.
90 *
91 * @param selector A selector to query for
92 * @param pageFunction Function to be evaluated in browser context
93 * @param x1 First argument to pass to pageFunction
94 * @returns Promise which resolves to the return value of pageFunction
95 */
96 $eval<R, X1>(
97 selector: string,
98 pageFunction: (element: Element, x1: UnwrapElementHandle<X1>) => R | Promise<R>,
99 x1: X1,
100 ): Promise<WrapElementHandle<R>>;
101
102 /**
103 * This method runs `document.querySelector` within the context and passes it as the first argument to `pageFunction`.
104 * If there's no element matching `selector`, the method throws an error.
105 *
106 * If `pageFunction` returns a Promise, then `$eval` would wait for the promise to resolve and return its value.
107 *
108 * @param selector A selector to query for
109 * @param pageFunction Function to be evaluated in browser context
110 * @param x1 First argument to pass to pageFunction
111 * @param x2 Second argument to pass to pageFunction
112 * @returns Promise which resolves to the return value of pageFunction
113 */
114 $eval<R, X1, X2>(
115 selector: string,
116 pageFunction: (element: Element, x1: UnwrapElementHandle<X1>, x2: UnwrapElementHandle<X2>) => R | Promise<R>,
117 x1: X1,
118 x2: X2,
119 ): Promise<WrapElementHandle<R>>;
120
121 /**
122 * This method runs `document.querySelector` within the context and passes it as the first argument to `pageFunction`.
123 * If there's no element matching `selector`, the method throws an error.
124 *
125 * If `pageFunction` returns a Promise, then `$eval` would wait for the promise to resolve and return its value.
126 *
127 * @param selector A selector to query for
128 * @param pageFunction Function to be evaluated in browser context
129 * @param x1 First argument to pass to pageFunction
130 * @param x2 Second argument to pass to pageFunction
131 * @param x3 Third argument to pass to pageFunction
132 * @returns Promise which resolves to the return value of pageFunction
133 */
134 $eval<R, X1, X2, X3>(
135 selector: string,
136 pageFunction: (
137 element: Element,
138 x1: UnwrapElementHandle<X1>,
139 x2: UnwrapElementHandle<X2>,
140 x3: UnwrapElementHandle<X3>,
141 ) => R | Promise<R>,
142 x1: X1,
143 x2: X2,
144 x3: X3,
145 ): Promise<WrapElementHandle<R>>;
146
147 /**
148 * This method runs `document.querySelector` within the context and passes it as the first argument to `pageFunction`.
149 * If there's no element matching `selector`, the method throws an error.
150 *
151 * If `pageFunction` returns a Promise, then `$eval` would wait for the promise to resolve and return its value.
152 *
153 * @param selector A selector to query for
154 * @param pageFunction Function to be evaluated in browser context
155 * @param args Arguments to pass to pageFunction
156 * @returns Promise which resolves to the return value of pageFunction
157 */
158 $eval<R>(
159 selector: string,
160 pageFunction: (element: Element, ...args: any[]) => R | Promise<R>,
161 ...args: SerializableOrJSHandle[]
162 ): Promise<WrapElementHandle<R>>;
163
164 /**
165 * This method runs `Array.from(document.querySelectorAll(selector))` within the context and passes it as the
166 * first argument to `pageFunction`.
167 *
168 * If `pageFunction` returns a Promise, then `$$eval` would wait for the promise to resolve and return its value.
169 *
170 * @param selector A selector to query for
171 * @param pageFunction Function to be evaluated in browser context
172 * @returns Promise which resolves to the return value of pageFunction
173 */
174 $$eval<R>(selector: string, pageFunction: (elements: Element[]) => R | Promise<R>): Promise<WrapElementHandle<R>>;
175
176 /**
177 * This method runs `Array.from(document.querySelectorAll(selector))` within the context and passes it as the
178 * first argument to `pageFunction`.
179 *
180 * If `pageFunction` returns a Promise, then `$$eval` would wait for the promise to resolve and return its value.
181 *
182 * @param selector A selector to query for
183 * @param pageFunction Function to be evaluated in browser context
184 * @param x1 First argument to pass to pageFunction
185 * @returns Promise which resolves to the return value of pageFunction
186 */
187 $$eval<R, X1>(
188 selector: string,
189 pageFunction: (elements: Element[], x1: UnwrapElementHandle<X1>) => R | Promise<R>,
190 x1: X1,
191 ): Promise<WrapElementHandle<R>>;
192
193 /**
194 * This method runs `Array.from(document.querySelectorAll(selector))` within the context and passes it as the
195 * first argument to `pageFunction`.
196 *
197 * If `pageFunction` returns a Promise, then `$$eval` would wait for the promise to resolve and return its value.
198 *
199 * @param selector A selector to query for
200 * @param pageFunction Function to be evaluated in browser context
201 * @param x1 First argument to pass to pageFunction
202 * @param x2 Second argument to pass to pageFunction
203 * @returns Promise which resolves to the return value of pageFunction
204 */
205 $$eval<R, X1, X2>(
206 selector: string,
207 pageFunction: (elements: Element[], x1: UnwrapElementHandle<X1>, x2: UnwrapElementHandle<X2>) => R | Promise<R>,
208 x1: X1,
209 x2: X2,
210 ): Promise<WrapElementHandle<R>>;
211
212 /**
213 * This method runs `Array.from(document.querySelectorAll(selector))` within the context and passes it as the
214 * first argument to `pageFunction`.
215 *
216 * If `pageFunction` returns a Promise, then `$$eval` would wait for the promise to resolve and return its value.
217 *
218 * @param selector A selector to query for
219 * @param pageFunction Function to be evaluated in browser context
220 * @param x1 First argument to pass to pageFunction
221 * @param x2 Second argument to pass to pageFunction
222 * @param x3 Third argument to pass to pageFunction
223 * @returns Promise which resolves to the return value of pageFunction
224 */
225 $$eval<R, X1, X2, X3>(
226 selector: string,
227 pageFunction: (
228 elements: Element[],
229 x1: UnwrapElementHandle<X1>,
230 x2: UnwrapElementHandle<X2>,
231 x3: UnwrapElementHandle<X3>,
232 ) => R | Promise<R>,
233 x1: X1,
234 x2: X2,
235 x3: X3,
236 ): Promise<WrapElementHandle<R>>;
237
238 /**
239 * This method runs `Array.from(document.querySelectorAll(selector))` within the context and passes it as the
240 * first argument to `pageFunction`.
241 *
242 * If `pageFunction` returns a Promise, then `$$eval` would wait for the promise to resolve and return its value.
243 *
244 * @param selector A selector to query for
245 * @param pageFunction Function to be evaluated in browser context
246 * @param args Arguments to pass to pageFunction
247 * @returns Promise which resolves to the return value of pageFunction
248 */
249 $$eval<R>(
250 selector: string,
251 pageFunction: (elements: Element[], ...args: any[]) => R | Promise<R>,
252 ...args: SerializableOrJSHandle[]
253 ): Promise<WrapElementHandle<R>>;
254}
255
256export interface JSEvalable<A = any> {
257 /**
258 * Evaluates a function in the browser context.
259 * If the function, passed to the frame.evaluate, returns a Promise, then frame.evaluate would wait for the promise to resolve and return its value.
260 * If the function passed into frame.evaluate returns a non-Serializable value, then frame.evaluate resolves to undefined.
261 * @param fn Function to be evaluated in browser context
262 * @param args Arguments to pass to `fn`
263 */
264 evaluate<T extends EvaluateFn<A>>(
265 pageFunction: T,
266 ...args: SerializableOrJSHandle[]
267 ): Promise<EvaluateFnReturnType<T> extends PromiseLike<infer U> ? U : EvaluateFnReturnType<T>>;
268 /**
269 * The only difference between `evaluate` and `evaluateHandle` is that `evaluateHandle` returns in-page object (`JSHandle`).
270 * If the function, passed to the `evaluateHandle`, returns a `Promise`, then `evaluateHandle` would wait for the
271 * promise to resolve and return its value.
272 * @param fn Function to be evaluated in browser context
273 * @param args Arguments to pass to `fn`
274 */
275 evaluateHandle(
276 pageFunction: string | ((arg1: A, ...args: any[]) => any),
277 ...args: SerializableOrJSHandle[]
278 ): Promise<JSHandle>;
279}
280
281/** Keyboard provides an api for managing a virtual keyboard. */
282export interface Keyboard {
283 /**
284 * Dispatches a keydown event.
285 * @param key Name of key to press, such as ArrowLeft.
286 * @param options Specifies a input text event.
287 */
288 down(key: string, options?: { text?: string }): Promise<void>;
289
290 /** Shortcut for `keyboard.down` and `keyboard.up`. */
291 press(key: string, options?: { text?: string; delay?: number }): Promise<void>;
292
293 /** Dispatches a `keypress` and `input` event. This does not send a `keydown` or keyup `event`. */
294 sendCharacter(char: string): Promise<void>;
295
296 /**
297 * Sends a keydown, keypress/input, and keyup event for each character in the text.
298 * @param text A text to type into a focused element.
299 * @param options Specifies the typing options.
300 */
301 type(text: string, options?: { delay?: number }): Promise<void>;
302
303 /**
304 * Dispatches a keyup event.
305 * @param key Name of key to release, such as ArrowLeft.
306 */
307 up(key: string): Promise<void>;
308}
309
310export interface MousePressOptions {
311 /**
312 * left, right, or middle.
313 * @default left
314 */
315 button?: MouseButtons;
316 /**
317 * The number of clicks.
318 * @default 1
319 */
320 clickCount?: number;
321}
322
323export interface MouseWheelOptions {
324 deltaX?: number;
325 deltaY?: number;
326}
327
328export interface MouseWheelOptions {
329 /**
330 * X delta in CSS pixels for mouse wheel event. Positive values emulate a scroll up and negative values a scroll down event.
331 * @default 0
332 */
333 deltaX?: number;
334 /**
335 * Y delta in CSS pixels for mouse wheel event. Positive values emulate a scroll right and negative values a scroll left event.
336 * @default 0
337 */
338 deltaY?: number;
339}
340
341export interface Mouse {
342 /**
343 * Shortcut for `mouse.move`, `mouse.down` and `mouse.up`.
344 * @param x The x position.
345 * @param y The y position.
346 * @param options The click options.
347 */
348 click(x: number, y: number, options?: ClickOptions): Promise<void>;
349 /**
350 * Dispatches a `mousedown` event.
351 * @param options The mouse press options.
352 */
353 down(options?: MousePressOptions): Promise<void>;
354
355 /**
356 * Dispatches a `mousemove` event.
357 * @param x The x position.
358 * @param y The y position.
359 * @param options The mouse move options.
360 */
361 move(x: number, y: number, options?: { steps: number }): Promise<void>;
362 /**
363 * Dispatches a `mouseup` event.
364 * @param options The mouse press options.
365 */
366 up(options?: MousePressOptions): Promise<void>;
367
368 /**
369 * Dispatches a `mousewheel` event.
370 * @param options - Optional: `MouseWheelOptions`.
371 *
372 * @example
373 * An example of zooming into an element:
374 * ```js
375 * await page.goto('https://mdn.mozillademos.org/en-US/docs/Web/API/Element/wheel_event$samples/Scaling_an_element_via_the_wheel?revision=1587366');
376 *
377 * const elem = await page.$('div');
378 * const boundingBox = await elem.boundingBox();
379 * await page.mouse.move(
380 * boundingBox.x + boundingBox.width / 2,
381 * boundingBox.y + boundingBox.height / 2
382 * );
383 *
384 * await page.mouse.wheel({ deltaY: -100 })
385 * ```
386 */
387 wheel(options?: MouseWheelOptions): Promise<void>;
388}
389
390export interface Touchscreen {
391 /**
392 * Dispatches a touchstart and touchend event.
393 * @param x The x position.
394 * @param y The y position.
395 */
396 tap(x: number, y: number): Promise<void>;
397}
398/**
399 * You can use `tracing.start` and `tracing.stop` to create a trace file which can be opened in Chrome DevTools or timeline viewer.
400 */
401export interface Tracing {
402 start(options: TracingStartOptions): Promise<void>;
403 stop(): Promise<Buffer>;
404}
405
406export interface TracingStartOptions {
407 path?: string;
408 screenshots?: boolean;
409 categories?: string[];
410}
411
412export type DialogType = 'alert' | 'beforeunload' | 'confirm' | 'prompt';
413
414/** Dialog objects are dispatched by page via the 'dialog' event. */
415export interface Dialog {
416 /**
417 * Accepts the dialog.
418 * @param promptText A text to enter in prompt. Does not cause any effects if the dialog's type is not prompt.
419 */
420 accept(promptText?: string): Promise<void>;
421
422 /** If dialog is prompt, returns default prompt value. Otherwise, returns empty string. */
423 defaultValue(): string;
424
425 /** Dismiss the dialog */
426 dismiss(): Promise<void>;
427
428 /** Returns the message displayed in the dialog. */
429 message(): string;
430
431 /** The dialog type. Dialog's type, can be one of `alert`, `beforeunload`, `confirm` or `prompt`. */
432 type(): DialogType;
433}
434
435export type ConsoleMessageType =
436 | 'log'
437 | 'debug'
438 | 'info'
439 | 'error'
440 | 'warning'
441 | 'dir'
442 | 'dirxml'
443 | 'table'
444 | 'trace'
445 | 'clear'
446 | 'startGroup'
447 | 'startGroupCollapsed'
448 | 'endGroup'
449 | 'assert'
450 | 'profile'
451 | 'profileEnd'
452 | 'count'
453 | 'timeEnd';
454
455export interface ConsoleMessageLocation {
456 /**
457 * URL of the resource if known.
458 */
459 url?: string;
460 /**
461 * Line number in the resource if known
462 */
463 lineNumber?: number;
464 /**
465 * Column number in the resource if known.
466 */
467 columnNumber?: number;
468}
469
470/** ConsoleMessage objects are dispatched by page via the 'console' event. */
471export interface ConsoleMessage {
472 /** The message arguments. */
473 args(): JSHandle[];
474 /** The location the message originated from */
475 location(): ConsoleMessageLocation;
476 /** The message text. */
477 text(): string;
478 type(): ConsoleMessageType;
479}
480
481export interface AuthOptions {
482 username: string;
483 password: string;
484}
485
486export type MouseButtons = 'left' | 'right' | 'middle';
487
488export interface ClickOptions {
489 /** @default MouseButtons.Left */
490 button?: MouseButtons;
491 /** @default 1 */
492 clickCount?: number;
493 /**
494 * Time to wait between mousedown and mouseup in milliseconds.
495 * @default 0
496 */
497 delay?: number;
498}
499
500export type SameSiteSetting = 'Strict' | 'Lax';
501
502/** Represents a browser cookie. */
503export interface Cookie {
504 /** The cookie name. */
505 name: string;
506 /** The cookie value. */
507 value: string;
508 /** The cookie domain. */
509 domain: string;
510 /** The cookie path. */
511 path: string;
512 /** The cookie Unix expiration time in seconds. */
513 expires: number;
514 /** The cookie size */
515 size: number;
516 /** The cookie http only flag. */
517 httpOnly: boolean;
518 /** The session cookie flag. */
519 session: boolean;
520 /** The cookie secure flag. */
521 secure: boolean;
522 /** The cookie same site definition. */
523 sameSite: SameSiteSetting;
524}
525
526export interface DeleteCookie {
527 /** The cookie name. */
528 name: string;
529 url?: string;
530 domain?: string;
531 path?: string;
532}
533
534export interface SetCookie {
535 /** The cookie name. */
536 name: string;
537 /** The cookie value. */
538 value: string;
539 /** The request-URI to associate with the setting of the cookie. This value can affect the default domain and path values of the created cookie. */
540 url?: string;
541 /** The cookie domain. */
542 domain?: string;
543 /** The cookie path. */
544 path?: string;
545 /** The cookie Unix expiration time in seconds. */
546 expires?: number;
547 /** The cookie http only flag. */
548 httpOnly?: boolean;
549 /** The session cookie flag. */
550 session?: boolean;
551 /** The cookie secure flag. */
552 secure?: boolean;
553 /** The cookie same site definition. */
554 sameSite?: SameSiteSetting;
555}
556
557export interface Viewport {
558 /** The page width in pixels. */
559 width: number;
560 /** The page height in pixels. */
561 height: number;
562 /**
563 * Specify device scale factor (can be thought of as dpr).
564 * @default 1
565 */
566 deviceScaleFactor?: number;
567 /**
568 * Whether the `meta viewport` tag is taken into account.
569 * @default false
570 */
571 isMobile?: boolean;
572 /**
573 * Specifies if viewport supports touch events.
574 * @default false
575 */
576 hasTouch?: boolean;
577 /**
578 * Specifies if viewport is in landscape mode.
579 * @default false
580 */
581 isLandscape?: boolean;
582}
583
584/** Page emulation options. */
585export interface EmulateOptions {
586 /** The viewport emulation options. */
587 viewport: Viewport;
588 /** The emulated user-agent. */
589 userAgent: string;
590}
591
592export type EvaluateFn<T = any> = string | ((arg1: T, ...args: any[]) => any);
593export type EvaluateFnReturnType<T extends EvaluateFn> = T extends (...args: any[]) => infer R ? R : unknown;
594
595export type LoadEvent = 'load' | 'domcontentloaded' | 'networkidle0' | 'networkidle2';
596
597export interface Timeoutable {
598 /**
599 * Maximum navigation time in milliseconds, pass 0 to disable timeout.
600 * @default 30000
601 */
602 timeout?: number;
603}
604
605/** The navigation options. */
606export interface NavigationOptions extends Timeoutable {
607 /**
608 * When to consider navigation succeeded.
609 * @default load Navigation is consider when the `load` event is fired.
610 */
611 waitUntil?: LoadEvent | LoadEvent[];
612}
613
614/**
615 * Navigation options for `page.goto`.
616 */
617export interface DirectNavigationOptions extends NavigationOptions {
618 /**
619 * Referer header value.
620 * If provided it will take preference over the referer header value set by
621 * [page.setExtraHTTPHeaders()](#pagesetextrahttpheadersheaders).
622 */
623 referer?: string;
624}
625
626/** Accepts values labeled with units. If number, treat as pixels. */
627export type LayoutDimension = string | number;
628
629export type PDFFormat = 'Letter' | 'Legal' | 'Tabloid' | 'Ledger' | 'A0' | 'A1' | 'A2' | 'A3' | 'A4' | 'A5' | 'A6';
630
631export interface PDFOptions {
632 /**
633 * The file path to save the PDF to.
634 * If `path` is a relative path, then it is resolved relative to current working directory.
635 * If no path is provided, the PDF won't be saved to the disk.
636 */
637 path?: string;
638 /**
639 * Scale of the webpage rendering.
640 * @default 1
641 */
642 scale?: number;
643 /**
644 * Display header and footer.
645 * @default false
646 */
647 displayHeaderFooter?: boolean;
648 /**
649 * HTML template for the print header. Should be valid HTML markup with following classes used to inject printing values into them:
650 * - `date` formatted print date
651 * - `title` document title
652 * - `url` document location
653 * - `pageNumber` current page number
654 * - `totalPages` total pages in the document
655 */
656 headerTemplate?: string;
657 /**
658 * HTML template for the print footer. Should be valid HTML markup with following classes used to inject printing values into them:
659 * - `date` formatted print date
660 * - `title` document title
661 * - `url` document location
662 * - `pageNumber` current page number
663 * - `totalPages` total pages in the document
664 */
665 footerTemplate?: string;
666 /**
667 * Print background graphics.
668 * @default false
669 */
670 printBackground?: boolean;
671 /**
672 * Paper orientation.
673 * @default false
674 */
675 landscape?: boolean;
676 /**
677 * Paper ranges to print, e.g., '1-5, 8, 11-13'.
678 * @default '' which means print all pages.
679 */
680 pageRanges?: string;
681 /**
682 * Paper format. If set, takes priority over width or height options.
683 * @default 'Letter'
684 */
685 format?: PDFFormat;
686 /** Paper width. */
687 width?: LayoutDimension;
688 /** Paper height. */
689 height?: LayoutDimension;
690 /** Paper margins, defaults to none. */
691 margin?: {
692 /** Top margin. */
693 top?: LayoutDimension;
694 /** Right margin. */
695 right?: LayoutDimension;
696 /** Bottom margin. */
697 bottom?: LayoutDimension;
698 /** Left margin. */
699 left?: LayoutDimension;
700 };
701 /**
702 * Give any CSS @page size declared in the page priority over what is declared in width and
703 * height or format options.
704 * @default false which will scale the content to fit the paper size.
705 */
706 preferCSSPageSize?: boolean;
707}
708
709/** Defines the screenshot options. */
710export interface ScreenshotOptions {
711 /**
712 * The file path to save the image to. The screenshot type will be inferred from file extension.
713 * If `path` is a relative path, then it is resolved relative to current working directory.
714 * If no path is provided, the image won't be saved to the disk.
715 */
716 path?: string;
717 /**
718 * The screenshot type.
719 * @default png
720 */
721 type?: 'jpeg' | 'png';
722 /** The quality of the image, between 0-100. Not applicable to png images. */
723 quality?: number;
724 /**
725 * When true, takes a screenshot of the full scrollable page.
726 * @default false
727 */
728 fullPage?: boolean;
729 /**
730 * An object which specifies clipping region of the page.
731 */
732 clip?: BoundingBox;
733 /**
734 * Hides default white background and allows capturing screenshots with transparency.
735 * @default false
736 */
737 omitBackground?: boolean;
738 /**
739 * The encoding of the image, can be either base64 or binary.
740 * @default binary
741 */
742 encoding?: 'base64' | 'binary';
743}
744
745export interface BinaryScreenShotOptions extends ScreenshotOptions {
746 encoding?: 'binary';
747}
748
749export interface Base64ScreenShotOptions extends ScreenshotOptions {
750 encoding: 'base64';
751}
752
753/** Options for `addStyleTag` */
754export interface StyleTagOptions {
755 /** Url of the <link> tag. */
756 url?: string;
757 /** Path to the CSS file to be injected into frame. If `path` is a relative path, then it is resolved relative to current working directory. */
758 path?: string;
759 /** Raw CSS content to be injected into frame. */
760 content?: string;
761}
762/** Options for `addScriptTag` */
763export interface ScriptTagOptions {
764 /** Url of a script to be added. */
765 url?: string;
766 /** Path to the JavaScript file to be injected into frame. If `path` is a relative path, then it is resolved relative to current working directory. */
767 path?: string;
768 /** Raw JavaScript content to be injected into frame. */
769 content?: string;
770 /** Script type. Use 'module' in order to load a Javascript ES6 module. */
771 type?: string;
772}
773
774export interface PageFnOptions extends Timeoutable {
775 polling?: 'raf' | 'mutation' | number;
776}
777
778export interface BoundingBox {
779 /** The x-coordinate of top-left corner. */
780 x: number;
781 /** The y-coordinate of top-left corner. */
782 y: number;
783 /** The width. */
784 width: number;
785 /** The height. */
786 height: number;
787}
788
789export interface BoxModel {
790 /** Content box, represented as an array of {x, y} points. */
791 content: Box[];
792 /** Padding box, represented as an array of {x, y} points. */
793 padding: Box[];
794 /** Border box, represented as an array of {x, y} points. */
795 border: Box[];
796 /** Margin box, represented as an array of {x, y} points. */
797 margin: Box[];
798 width: number;
799 height: number;
800}
801
802export interface Box {
803 x: number;
804 y: number;
805}
806
807/**
808 * The Worker class represents a WebWorker.
809 * The events workercreated and workerdestroyed are emitted on the page object to signal the worker lifecycle.
810 */
811export interface Worker extends JSEvalable {
812 executionContext(): Promise<ExecutionContext>;
813
814 url(): string;
815}
816
817/**
818 * Represents an in-page DOM element. ElementHandles can be created with the page.$ method.
819 */
820export interface ElementHandle<E extends Element = Element> extends JSHandle<E>, Evalable {
821 /**
822 * The method runs element.querySelector within the page.
823 * If no element matches the selector, the return value resolve to null.
824 * @param selector A selector to query element for
825 * @since 0.13.0
826 */
827 $(selector: string): Promise<ElementHandle | null>;
828
829 /**
830 * The method runs element.querySelectorAll within the page.
831 * If no elements match the selector, the return value resolve to [].
832 * @param selector A selector to query element for
833 * @since 0.13.0
834 */
835 $$(selector: string): Promise<ElementHandle[]>;
836
837 /**
838 * @param selector XPath expression to evaluate.
839 */
840 $x(expression: string): Promise<ElementHandle[]>;
841 /**
842 * This method returns the value resolve to the bounding box of the element (relative to the main frame), or null if the element is not visible.
843 */
844 boundingBox(): Promise<BoundingBox | null>;
845 /**
846 * This method returns boxes of the element, or null if the element is not visible.
847 * Boxes are represented as an array of points; each Point is an object {x, y}. Box points are sorted clock-wise.
848 */
849 boxModel(): Promise<BoxModel | null>;
850 /**
851 * This method scrolls element into view if needed, and then uses page.mouse to click in the center of the element.
852 * If the element is detached from DOM, the method throws an error.
853 * @param options Specifies the options.
854 * @since 0.9.0
855 */
856 click(options?: ClickOptions): Promise<void>;
857 /**
858 * @returns Resolves to the content frame for element handles referencing iframe nodes, or null otherwise.
859 * @since 1.2.0
860 */
861 contentFrame(): Promise<Frame | null>;
862 /**
863 * Calls focus on the element.
864 */
865 focus(): Promise<void>;
866 /**
867 * This method scrolls element into view if needed, and then uses page.mouse to hover over the center of the element.
868 * If the element is detached from DOM, the method throws an error.
869 */
870 hover(): Promise<void>;
871 /**
872 * Resolves to true if the element is visible in the current viewport.
873 */
874 isIntersectingViewport(): Promise<boolean>;
875 /**
876 * Focuses the element, and then uses keyboard.down and keyboard.up.
877 * @param key Name of key to press, such as ArrowLeft. See USKeyboardLayout for a list of all key names.
878 * @param options The text and delay options.
879 */
880 press(key: string, options?: { text?: string; delay?: number }): Promise<void>;
881 /**
882 * This method scrolls element into view if needed, and then uses page.screenshot to take a screenshot of the element.
883 * If the element is detached from DOM, the method throws an error.
884 * @param options Same options as in page.screenshot.
885 */
886 screenshot(options?: Base64ScreenShotOptions): Promise<string>;
887 screenshot(options?: BinaryScreenShotOptions): Promise<Buffer>;
888 screenshot(options?: ScreenshotOptions): Promise<string | Buffer>;
889 /**
890 * Triggers a change and input event once all the provided options have been selected. If there's no <select> element
891 * matching selector, the method throws an error.
892 * @param values Values of options to select. If the <select> has the multiple attribute, all values are considered, otherwise only the first one is taken into account.
893 * @returns An array of option values that have been successfully selected.
894 * @since 1.12.0
895 */
896 select(...values: string[]): Promise<string[]>;
897 /**
898 * This method scrolls element into view if needed, and then uses touchscreen.tap to tap in the center of the element.
899 * If the element is detached from DOM, the method throws an error.
900 */
901 tap(): Promise<void>;
902 toString(): string;
903 /**
904 * Focuses the element, and then sends a keydown, keypress/input, and keyup event for each character in the text.
905 * @param text A text to type into a focused element.
906 * @param options The typing options.
907 */
908 type(text: string, options?: { delay: number }): Promise<void>;
909 /**
910 * This method expects elementHandle to point to an input element.
911 * @param filePaths Sets the value of the file input these paths. If some of the filePaths are relative paths, then they are resolved relative to current working directory.
912 */
913 uploadFile(...filePaths: string[]): Promise<void>;
914}
915
916/** The class represents a context for JavaScript execution. */
917export interface ExecutionContext extends JSEvalable {
918 queryObjects(prototypeHandle: JSHandle): Promise<JSHandle>;
919}
920
921/** JSHandle represents an in-page JavaScript object. */
922export interface JSHandle<T = any> extends JSEvalable<T> {
923 /**
924 * Returns a ElementHandle
925 */
926 asElement(): ElementHandle | null;
927 /**
928 * Stops referencing the element handle.
929 */
930 dispose(): Promise<void>;
931 /**
932 * Gets the execution context.
933 */
934 executionContext(): ExecutionContext;
935 /**
936 * Returns a map with property names as keys and JSHandle instances for the property values.
937 */
938 getProperties(): Promise<Map<string, JSHandle>>;
939 /**
940 * Fetches a single property from the objectHandle.
941 * @param propertyName The property to get.
942 */
943 getProperty(propertyName: string): Promise<JSHandle>;
944
945 /**
946 * Returns a JSON representation of the object.
947 * The JSON is generated by running JSON.stringify on the object in page and consequent JSON.parse in puppeteer.
948 * @throws The method will throw if the referenced object is not stringifiable.
949 */
950 jsonValue(): Promise<unknown>;
951}
952
953export interface Metrics {
954 /** The timestamp when the metrics sample was taken. */
955 Timestamp: number;
956 /** Number of documents in the page. */
957 Documents: number;
958 /** Number of frames in the page. */
959 Frames: number;
960 /** Number of events in the page. */
961 JSEventListeners: number;
962 /** Number of DOM nodes in the page. */
963 Nodes: number;
964 /** Total number of full or partial page layout. */
965 LayoutCount: number;
966 /** Total number of page style recalculations. */
967 RecalcStyleCount: number;
968 /** Combined durations of all page layouts. */
969 LayoutDuration: number;
970 /** Combined duration of all page style recalculations. */
971 RecalcStyleDuration: number;
972 /** Combined duration of JavaScript execution. */
973 ScriptDuration: number;
974 /** Combined duration of all tasks performed by the browser. */
975 TaskDuration: number;
976 /** Used JavaScript heap size. */
977 JSHeapUsedSize: number;
978 /** Total JavaScript heap size. */
979 JSHeapTotalSize: number;
980}
981
982export type Headers = Record<string, string>;
983export type HttpMethod = 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE' | 'OPTIONS';
984
985export type ResourceType =
986 | 'document'
987 | 'stylesheet'
988 | 'image'
989 | 'media'
990 | 'font'
991 | 'script'
992 | 'texttrack'
993 | 'xhr'
994 | 'fetch'
995 | 'eventsource'
996 | 'websocket'
997 | 'manifest'
998 | 'other';
999
1000export type ErrorCode =
1001 | 'aborted'
1002 | 'accessdenied'
1003 | 'addressunreachable'
1004 | 'blockedbyclient'
1005 | 'blockedbyresponse'
1006 | 'connectionaborted'
1007 | 'connectionclosed'
1008 | 'connectionfailed'
1009 | 'connectionrefused'
1010 | 'connectionreset'
1011 | 'internetdisconnected'
1012 | 'namenotresolved'
1013 | 'timedout'
1014 | 'failed';
1015
1016export interface Overrides {
1017 url?: string;
1018 method?: HttpMethod;
1019 postData?: string;
1020 headers?: Headers;
1021}
1022
1023/** Represents a page request. */
1024export interface Request {
1025 /**
1026 * Aborts request.
1027 * To use this, request interception should be enabled with `page.setRequestInterception`.
1028 * @throws An exception is immediately thrown if the request interception is not enabled.
1029 */
1030 abort(errorCode?: ErrorCode): Promise<void>;
1031
1032 /**
1033 * Continues request with optional request overrides.
1034 * To use this, request interception should be enabled with `page.setRequestInterception`.
1035 * @throws An exception is immediately thrown if the request interception is not enabled.
1036 */
1037 continue(overrides?: Overrides): Promise<void>;
1038
1039 /**
1040 * @returns An object if the request failed, null otherwise.
1041 */
1042 failure(): { errorText: string } | null;
1043
1044 /**
1045 * @returns The `Frame` object that initiated the request, or `null` if navigating to error pages
1046 */
1047 frame(): Frame | null;
1048
1049 /**
1050 * An object with HTTP headers associated with the request.
1051 * All header names are lower-case.
1052 */
1053 headers(): Headers;
1054
1055 /** Whether this request is driving frame's navigation. */
1056 isNavigationRequest(): boolean;
1057
1058 /** Returns the request's method (GET, POST, etc.) */
1059
1060 method(): HttpMethod;
1061
1062 /** Contains the request's post body, if any. */
1063 postData(): string | undefined;
1064
1065 /**
1066 * A `redirectChain` is a chain of requests initiated to fetch a resource.
1067 *
1068 * - If there are no redirects and the request was successful, the chain will be empty.
1069 * - If a server responds with at least a single redirect, then the chain will contain all the requests that were redirected.
1070 *
1071 * `redirectChain` is shared between all the requests of the same chain.
1072 *
1073 * @since 1.2.0
1074 */
1075 redirectChain(): Request[];
1076
1077 /** Contains the request's resource type as it was perceived by the rendering engine. */
1078 resourceType(): ResourceType;
1079
1080 /**
1081 * Fulfills request with given response.
1082 * To use this, request interception should be enabled with `page.setRequestInterception`.
1083 * @throws An exception is immediately thrown if the request interception is not enabled.
1084 * @param response The response options that will fulfill this request.
1085 */
1086 respond(response: RespondOptions): Promise<void>;
1087
1088 /** A matching `Response` object, or `null` if the response has not been received yet. */
1089 response(): Response | null;
1090
1091 /** Contains the URL of the request. */
1092 url(): string;
1093}
1094/** Options for `Request.respond` method */
1095export interface RespondOptions {
1096 /**
1097 * Specifies the response status code.
1098 * @default 200
1099 */
1100 status?: number;
1101 /** Specifies the response headers. */
1102 headers?: Headers;
1103 /** Specifies the Content-Type response header. */
1104 contentType?: string;
1105 /** Specifies the response body. */
1106 body?: Buffer | string;
1107}
1108
1109export interface RemoteInfo {
1110 /** the IP address of the remote server */
1111 ip: string;
1112 /** the port used to connect to the remote server */
1113 port: number;
1114}
1115
1116export interface SecurityDetails {
1117 /** A string with the name of issuer of the certificate. (e.g. "Let's Encrypt Authority X3"). */
1118 issuer(): string;
1119 /** String with the security protocol (e.g. TLS 1.2). */
1120 protocol(): string;
1121 /** Name of the subject to which the certificate was issued to (e.g. "www.example.com"). */
1122 subjectName(): string;
1123 /** Timestamp stating the start of validity of the certificate. */
1124 validFrom(): number;
1125 /** Timestamp stating the end of validity of the certificate. */
1126 validTo(): number;
1127}
1128
1129/** Response class represents responses which are received by page. */
1130export interface Response {
1131 /** Promise which resolves to a buffer with response body. */
1132 buffer(): Promise<Buffer>;
1133 /** A Frame that initiated this response, or null if navigating to error pages. */
1134 frame(): Frame | null;
1135 /** True if the response was served from either the browser's disk cache or memory cache. */
1136 fromCache(): boolean;
1137 /** True if the response was served by a service worker. */
1138 fromServiceWorker(): boolean;
1139 /** An object with HTTP headers associated with the response. All header names are lower-case. */
1140 headers(): Headers;
1141 /**
1142 * Promise which resolves to a JSON representation of response body.
1143 * @throws This method will throw if the response body is not parsable via `JSON.parse`.
1144 */
1145 json(): Promise<unknown>;
1146 /** Contains a boolean stating whether the response was successful (status in the range 200-299) or not. */
1147 ok(): boolean;
1148 /** Returns remote connection info */
1149 remoteAddress(): RemoteInfo;
1150 /** Returns an object with security details associated with the response. */
1151 securityDetails(): SecurityDetails | null;
1152 /** A matching Request object. */
1153 request(): Request;
1154 /** Contains the status code of the response (e.g., 200 for a success). */
1155 status(): number;
1156 /** Contains the status text of the response (e.g. usually an "OK" for a success). */
1157 statusText(): string;
1158 /** Promise which resolves to a text representation of response body. */
1159 text(): Promise<string>;
1160 /** Contains the URL of the response. */
1161 url(): string;
1162}
1163
1164export interface WaitForSelectorOptions extends Timeoutable {
1165 /**
1166 * Wait for element to be present in DOM and to be visible,
1167 * i.e. to not have display: none or visibility: hidden CSS properties.
1168 * @default false
1169 */
1170 visible?: boolean;
1171 /**
1172 * Wait for element to not be found in the DOM or to be hidden,
1173 * i.e. have display: none or visibility: hidden CSS properties.
1174 * @default false
1175 */
1176 hidden?: boolean;
1177}
1178
1179export interface WaitForSelectorOptionsHidden extends WaitForSelectorOptions {
1180 hidden: true;
1181}
1182
1183export interface FrameBase extends Evalable, JSEvalable {
1184 /**
1185 * The method queries frame for the selector.
1186 * If there's no such element within the frame, the method will resolve to null.
1187 */
1188 $(selector: string): Promise<ElementHandle | null>;
1189
1190 /**
1191 * The method runs document.querySelectorAll within the frame.
1192 * If no elements match the selector, the return value resolve to [].
1193 */
1194 $$(selector: string): Promise<ElementHandle[]>;
1195
1196 /**
1197 * The method evaluates the XPath expression.
1198 * @param expression XPath expression to evaluate.
1199 */
1200 $x(expression: string): Promise<ElementHandle[]>;
1201
1202 /** Adds a `<script>` tag into the page with the desired url or content. */
1203 addScriptTag(options: ScriptTagOptions): Promise<void>;
1204
1205 /** Adds a `<link rel="stylesheet">` tag into the page with the desired url or a `<style type="text/css">` tag with the content. */
1206 addStyleTag(options: StyleTagOptions): Promise<void>;
1207
1208 /**
1209 * This method fetches an element with selector, scrolls it into view if needed, and
1210 * then uses `page.mouse` to click in the center of the element. If there's no element
1211 * matching selector, the method throws an error.
1212 * @param selector A selector to search for element to click. If there are multiple elements satisfying the selector, the first will be clicked.
1213 * @param options Specifies the click options.
1214 */
1215 click(selector: string, options?: ClickOptions): Promise<void>;
1216
1217 /** Gets the full HTML contents of the page, including the doctype. */
1218 content(): Promise<string>;
1219
1220 /**
1221 * Navigates to a URL.
1222 * @param url URL to navigate page to. The url should include scheme, e.g. `https://`
1223 * @param options The navigation parameters.
1224 */
1225 goto(url: string, options?: DirectNavigationOptions): Promise<Response | null>;
1226
1227 /** This method fetches an element with selector and focuses it. */
1228 focus(selector: string): Promise<void>;
1229
1230 /**
1231 * This method fetches an element with `selector`, scrolls it into view if needed,
1232 * and then uses page.mouse to hover over the center of the element. If there's no
1233 * element matching `selector`, the method throws an error.
1234 * @param selector A selector to search for element to hover. If there are multiple elements satisfying the selector, the first will be hovered.
1235 */
1236 hover(selector: string): Promise<void>;
1237
1238 /**
1239 * Triggers a `change` and `input` event once all the provided options have been selected.
1240 * If there's no `<select>` element matching selector, the method throws an error.
1241 * @param selector A selector to query page for.
1242 * @param values Values of options to select. If the `<select>` has the `multiple` attribute,
1243 * all values are considered, otherwise only the first one is taken into account.
1244 */
1245 select(selector: string, ...values: string[]): Promise<string[]>;
1246
1247 /**
1248 * Sets the page content.
1249 * @param html HTML markup to assign to the page.
1250 * @param options The navigation parameters.
1251 */
1252 setContent(html: string, options?: NavigationOptions): Promise<void>;
1253
1254 /**
1255 * This method fetches an element with `selector`, scrolls it into view if needed,
1256 * and then uses page.touchscreen to tap in the center of the element.
1257 * @param selector A `selector` to search for element to tap. If there are multiple elements
1258 * satisfying the selector, the first will be tapped.
1259 */
1260 tap(selector: string): Promise<void>;
1261
1262 /** Returns page's title. */
1263 title(): Promise<string>;
1264
1265 /**
1266 * Sends a `keydown`, `keypress/input`, and `keyup` event for each character in the text.
1267 * @param selector A selector of an element to type into. If there are multiple elements satisfying the selector, the first will be used.
1268 * @param text: A text to type into a focused element.
1269 * @param options: The typing parameters.
1270 */
1271 type(selector: string, text: string, options?: { delay: number }): Promise<void>;
1272
1273 /** Returns frame's url. */
1274 url(): string;
1275
1276 /**
1277 * @remarks
1278 *
1279 * This method behaves differently depending on the first parameter. If it's a
1280 * `string`, it will be treated as a `selector` or `xpath` (if the string
1281 * starts with `//`). This method then is a shortcut for
1282 * {@link Frame.waitForSelector} or {@link Frame.waitForXPath}.
1283 *
1284 * If the first argument is a function this method is a shortcut for
1285 * {@link Frame.waitForFunction}.
1286 *
1287 * If the first argument is a `number`, it's treated as a timeout in
1288 * milliseconds and the method returns a promise which resolves after the
1289 * timeout.
1290 *
1291 * @param selectorOrFunctionOrTimeout - a selector, predicate or timeout to
1292 * wait for.
1293 * @param options - optional waiting parameters.
1294 * @param args - arguments to pass to `pageFunction`.
1295 *
1296 * @deprecated Don't use this method directly. Instead use the more explicit
1297 * methods available: {@link Frame.waitForSelector},
1298 * {@link Frame.waitForXPath}, {@link Frame.waitForFunction} or
1299 * {@link Frame.waitForTimeout}.
1300 */
1301 waitFor(duration: number): Promise<void>;
1302 waitFor(selector: string, options: WaitForSelectorOptionsHidden): Promise<ElementHandle | null>;
1303 waitFor(selector: string, options?: WaitForSelectorOptions): Promise<ElementHandle>;
1304 waitFor(
1305 selector: EvaluateFn,
1306 options?: WaitForSelectorOptions,
1307 ...args: SerializableOrJSHandle[]
1308 ): Promise<JSHandle>;
1309
1310 /**
1311 * Allows waiting for various conditions.
1312 */
1313 waitForFunction(fn: EvaluateFn, options?: PageFnOptions, ...args: SerializableOrJSHandle[]): Promise<JSHandle>;
1314
1315 /**
1316 * Wait for the page navigation occur.
1317 * @param options The navigation parameters.
1318 */
1319 waitForNavigation(options?: NavigationOptions): Promise<Response>;
1320
1321 waitForSelector(selector: string, options?: WaitForSelectorOptions): Promise<ElementHandle>;
1322 waitForSelector(selector: string, options?: WaitForSelectorOptionsHidden): Promise<ElementHandle | null>;
1323
1324 /**
1325 * Causes your script to wait for the given number of milliseconds.
1326 *
1327 * @remarks
1328 * It's generally recommended to not wait for a number of seconds, but instead
1329 * use {@link Frame.waitForSelector}, {@link Frame.waitForXPath} or
1330 * {@link Frame.waitForFunction} to wait for exactly the conditions you want.
1331 *
1332 * @example
1333 *
1334 * Wait for 1 second:
1335 *
1336 * ```
1337 * await frame.waitForTimeout(1000);
1338 * ```
1339 *
1340 * @param milliseconds - the number of milliseconds to wait.
1341 */
1342 waitForTimeout(milliseconds: number): Promise<void>;
1343
1344 waitForXPath(xpath: string, options?: WaitForSelectorOptions): Promise<ElementHandle>;
1345}
1346
1347export interface Frame extends FrameBase {
1348 childFrames(): Frame[];
1349 /** Execution context associated with this frame. */
1350 executionContext(): Promise<ExecutionContext>;
1351 /** Returns `true` if the frame has been detached, or `false` otherwise. */
1352 isDetached(): boolean;
1353 /** Returns frame's name attribute as specified in the tag. */
1354 name(): string;
1355 /** Returns parent frame, if any. Detached frames and main frames return null. */
1356 parentFrame(): Frame | null;
1357}
1358
1359export interface PageEventObj {
1360 /** Emitted when the page closes. */
1361 close: undefined;
1362 /**
1363 * Emitted when JavaScript within the page calls one of console API methods, e.g. console.log or console.dir.
1364 * Also emitted if the page throws an error or a warning.
1365 */
1366 console: ConsoleMessage;
1367 /**
1368 * Emitted when a JavaScript dialog appears, such as alert, prompt, confirm or beforeunload.
1369 * Puppeteer can respond to the dialog via Dialog's accept or dismiss methods.
1370 */
1371 dialog: Dialog;
1372 /**
1373 * Emitted when the initial HTML document has been completely loaded and parsed,
1374 * without waiting for stylesheets, images, and subframes to finish loading.
1375 */
1376 domcontentloaded: never;
1377 /** Emitted when the page crashes. */
1378 error: Error;
1379 /** Emitted when a frame is attached. */
1380 frameattached: Frame;
1381 /** Emitted when a frame is detached. */
1382 framedetached: Frame;
1383 /** Emitted when a frame is navigated to a new url. */
1384 framenavigated: Frame;
1385 /** Emitted when the JavaScript load event is dispatched. */
1386 load: undefined;
1387 /**
1388 * Emitted when the JavaScript code makes a call to `console.timeStamp`.
1389 * For the list of metrics see `page.metrics`.
1390 */
1391 metrics: { title: string; metrics: Metrics };
1392 /** Emitted when an uncaught exception happens within the page. */
1393 pageerror: Error;
1394 /** Emitted when the page opens a new tab or window. */
1395 popup: Page;
1396 /**
1397 * Emitted when a page issues a request. The request object is read-only.
1398 * In order to intercept and mutate requests, see page.setRequestInterceptionEnabled.
1399 */
1400 request: Request;
1401 /** Emitted when a request fails, for example by timing out. */
1402 requestfailed: Request;
1403 /** Emitted when a request finishes successfully. */
1404 requestfinished: Request;
1405 /** Emitted when a response is received. */
1406 response: Response;
1407 /** Emitted when a dedicated WebWorker is spawned by the page. */
1408 workercreated: Worker;
1409 /** Emitted when a dedicated WebWorker is terminated. */
1410 workerdestroyed: Worker;
1411}
1412
1413export interface PageCloseOptions {
1414 /**
1415 * Whether to run the before unload page handlers.
1416 * @default false
1417 */
1418 runBeforeUnload?: boolean;
1419}
1420
1421export interface GeoOptions {
1422 /**
1423 * Latitude between -90 and 90.
1424 */
1425 latitude: number;
1426 /**
1427 * Longitude between -180 and 180.
1428 */
1429 longitude: number;
1430 /**
1431 * Non-negative accuracy value.
1432 */
1433 accuracy?: number;
1434}
1435
1436export type MediaType = 'screen' | 'print';
1437
1438export interface AXNode {
1439 /**
1440 * The role.
1441 */
1442 role: string;
1443 /**
1444 * A human readable name for the node.
1445 */
1446 name: string;
1447 /**
1448 * The current value of the node.
1449 */
1450 value: string | number;
1451 /**
1452 * An additional human readable description of the node.
1453 */
1454 description: string;
1455 /**
1456 * Keyboard shortcuts associated with this node.
1457 */
1458 keyshortcuts: string;
1459 /**
1460 * A human readable alternative to the role.
1461 */
1462 roledescription: string;
1463 /**
1464 * A description of the current value.
1465 */
1466 valuetext: string;
1467 /**
1468 * Whether the node is disabled.
1469 */
1470 disabled: boolean;
1471 /**
1472 * Whether the node is expanded or collapsed.
1473 */
1474 expanded: boolean;
1475 /**
1476 * Whether the node is focused.
1477 */
1478 focused: boolean;
1479 /**
1480 * Whether the node is modal.
1481 */
1482 modal: boolean;
1483 /**
1484 * Whether the node text input supports multiline.
1485 */
1486 multiline: boolean;
1487 /**
1488 * Whether more than one child can be selected.
1489 */
1490 multiselectable: boolean;
1491 /**
1492 * Whether the node is read only.
1493 */
1494 readonly: boolean;
1495 /**
1496 * Whether the node is required.
1497 */
1498 required: boolean;
1499 /**
1500 * Whether the node is selected in its parent node.
1501 */
1502 selected: boolean;
1503 /**
1504 * Whether the checkbox is checked, or "mixed".
1505 */
1506 checked: boolean | 'mixed';
1507 /**
1508 * Whether the toggle button is checked, or "mixed".
1509 */
1510 pressed: boolean | 'mixed';
1511 /**
1512 * The level of a heading.
1513 */
1514 level: number;
1515 /**
1516 * The minimum value in a node.
1517 */
1518 valuemin: number;
1519 /**
1520 * The maximum value in a node.
1521 */
1522 valuemax: number;
1523 /**
1524 * What kind of autocomplete is supported by a control.
1525 */
1526 autocomplete: string;
1527 /**
1528 * What kind of popup is currently being shown for a node.
1529 */
1530 haspopup: string;
1531 /**
1532 * Whether and in what way this node's value is invalid.
1533 */
1534 invalid: string;
1535 /**
1536 * Whether the node is oriented horizontally or vertically.
1537 */
1538 orientation: string;
1539 /**
1540 * Child nodes of this node, if any.
1541 */
1542 children: AXNode[];
1543}
1544
1545export interface SnapshopOptions {
1546 /**
1547 * Prune uninteresting nodes from the tree.
1548 * @default true
1549 */
1550 interestingOnly?: boolean;
1551 /**
1552 * The root DOM element for the snapshot.
1553 * @default document.body
1554 */
1555 root?: ElementHandle;
1556}
1557
1558/**
1559 * The Accessibility class provides methods for inspecting Chromium's accessibility tree.
1560 * The accessibility tree is used by assistive technology such as screen readers.
1561 * Accessibility is a very platform-specific thing. On different platforms,
1562 * there are different screen readers that might have wildly different output.
1563 * Blink - Chrome's rendering engine - has a concept of "accessibility tree",
1564 * which is than translated into different platform-specific APIs.
1565 * Accessibility namespace gives users access to the Blink Accessibility Tree.
1566 * Most of the accessibility tree gets filtered out when converting from Blink AX Tree to Platform-specific AX-Tree or
1567 * by screen readers themselves. By default, Puppeteer tries to approximate this filtering,
1568 * exposing only the "interesting" nodes of the tree.
1569 */
1570export interface Accessibility {
1571 snapshot(options?: SnapshopOptions): Promise<AXNode>;
1572}
1573
1574export interface MediaFeature {
1575 name: string;
1576 value: string;
1577}
1578
1579export interface FileChooser {
1580 /**
1581 * Accept the file chooser request with given paths.
1582 * If some of the filePaths are relative paths, then they are resolved relative to the current working directory.
1583 */
1584 accept(filePaths: string[]): Promise<void>;
1585 /** Closes the file chooser without selecting any files. */
1586 cancel(): Promise<void>;
1587 /** Whether file chooser allow for multiple file selection. */
1588 isMultiple(): boolean;
1589}
1590
1591/** Page provides methods to interact with a single tab in Chromium. One Browser instance might have multiple Page instances. */
1592export interface Page extends EventEmitter, FrameBase {
1593 /**
1594 * Adds the listener function to the end of the listeners array for the event named `eventName`.
1595 * No checks are made to see if the listener has already been added. Multiple calls passing the same combination of
1596 * `eventName` and listener will result in the listener being added, and called, multiple times.
1597 * @param event The name of the event.
1598 * @param handler The callback function.
1599 */
1600 on<K extends keyof PageEventObj>(eventName: K, handler: (e: PageEventObj[K], ...args: any[]) => void): this;
1601
1602 /**
1603 * Adds a one time listener function for the event named `eventName`.
1604 * The next time `eventName` is triggered, this listener is removed and then invoked.
1605 * @param event The name of the event.
1606 * @param handler The callback function.
1607 */
1608 once<K extends keyof PageEventObj>(eventName: K, handler: (e: PageEventObj[K], ...args: any[]) => void): this;
1609
1610 accessibility: Accessibility;
1611
1612 /**
1613 * Provide credentials for http authentication.
1614 * To disable authentication, pass `null`.
1615 */
1616 authenticate(credentials: AuthOptions | null): Promise<void>;
1617
1618 /** Brings page to front (activates tab). */
1619 bringToFront(): Promise<void>;
1620
1621 /** Get the browser the page belongs to. */
1622 browser(): Browser;
1623
1624 /** Get the browser context that the page belongs to. */
1625 browserContext(): BrowserContext;
1626
1627 /** Closes the current page. */
1628 close(options?: PageCloseOptions): Promise<void>;
1629
1630 /**
1631 * Gets the cookies.
1632 * If no URLs are specified, this method returns cookies for the current page URL.
1633 * If URLs are specified, only cookies for those URLs are returned.
1634 */
1635 cookies(...urls: string[]): Promise<Cookie[]>;
1636
1637 coverage: Coverage;
1638
1639 /**
1640 * Deletes the specified cookies.
1641 */
1642 deleteCookie(...cookies: DeleteCookie[]): Promise<void>;
1643
1644 /** Emulates given device metrics and user agent. This method is a shortcut for `setUserAgent` and `setViewport`. */
1645 emulate(options: EmulateOptions): Promise<void>;
1646
1647 /**
1648 * Emulates the idle state.
1649 * If no arguments set, clears idle state emulation.
1650 *
1651 * @example
1652 * ```js
1653 * // set idle emulation
1654 * await page.emulateIdleState({isUserActive: true, isScreenUnlocked: false});
1655 *
1656 * // do some checks here
1657 * ...
1658 *
1659 * // clear idle emulation
1660 * await page.emulateIdleState();
1661 * ```
1662 *
1663 * @param overrides Mock idle state. If not set, clears idle overrides
1664 * @param isUserActive Mock isUserActive
1665 * @param isScreenUnlocked Mock isScreenUnlocked
1666 */
1667 emulateIdleState(overrides?: { isUserActive: boolean; isScreenUnlocked: boolean }): Promise<void>;
1668
1669 /** Emulates the media. */
1670 emulateMediaType(mediaType: MediaType | null): Promise<void>;
1671
1672 /**
1673 * Given an array of media feature objects, emulates CSS media features on the page.
1674 * Passing null resets all.
1675 */
1676 emulateMediaFeatures(features: MediaFeature[] | null): Promise<void>;
1677
1678 /**
1679 * Changes the timezone of the page.
1680 * See ICU’s [metaZones.txt](https://cs.chromium.org/chromium/src/third_party/icu/source/data/misc/metaZones.txt?rcl=faee8bc70570192d82d2978a71e2a615788597d1) for a list of supported timezone IDs.
1681 * Passing null disables timezone emulation.
1682 */
1683 emulateTimezone(tz: string | null): Promise<void>;
1684
1685 /**
1686 * Adds a function which would be invoked in one of the following scenarios: whenever the page is navigated; whenever the child frame is attached or navigated.
1687 * The function is invoked after the document was created but before any of its scripts were run. This is useful to amend JavaScript environment, e.g. to seed Math.random.
1688 * @param fn The function to be evaluated in browser context.
1689 * @param args The arguments to pass to the `fn`.
1690 */
1691 evaluateOnNewDocument(fn: EvaluateFn, ...args: SerializableOrJSHandle[]): Promise<void>;
1692
1693 /**
1694 * The method adds a function called name on the page's `window` object.
1695 * When called, the function executes `puppeteerFunction` in node.js and returns a
1696 * Promise which resolves to the return value of `puppeteerFunction`.
1697 * @param name The name of the function on the window object.
1698 * @param fn Callback function which will be called in Puppeteer's context.
1699 */
1700 exposeFunction(name: string, puppeteerFunction: (...args: any[]) => any): Promise<void>;
1701
1702 /** An array of all frames attached to the page. */
1703 frames(): Frame[];
1704
1705 /**
1706 * Navigate to the previous page in history.
1707 * @param options The navigation parameters.
1708 */
1709 goBack(options?: NavigationOptions): Promise<Response | null>;
1710
1711 /**
1712 * Navigate to the next page in history.
1713 * @param options The navigation parameters.
1714 */
1715 goForward(options?: NavigationOptions): Promise<Response | null>;
1716
1717 /** Returns the virtual keyboard. */
1718 keyboard: Keyboard;
1719
1720 /** Indicates that the page has been closed. */
1721 isClosed(): boolean;
1722
1723 /**
1724 * @returns `true` if the page has JavaScript enabled, `false` otherwise.
1725 */
1726 isJavaScriptEnabled(): boolean;
1727
1728 /** Page is guaranteed to have a main frame which persists during navigation's. */
1729 mainFrame(): Frame;
1730
1731 /** Gets the page metrics. */
1732 metrics(): Promise<Metrics>;
1733
1734 /** Gets the virtual mouse. */
1735 mouse: Mouse;
1736
1737 /**
1738 * Generates a PDF of the page with `print` css media.
1739 * To generate a pdf with `screen` media, call `page.emulateMedia('screen')` before calling `page.pdf()`:
1740 * @param options The PDF parameters.
1741 */
1742 pdf(options?: PDFOptions): Promise<Buffer>;
1743
1744 /**
1745 * The method iterates JavaScript heap and finds all the objects with the given prototype.
1746 * @param prototypeHandle A handle to the object prototype.
1747 */
1748 queryObjects(prototypeHandle: JSHandle): Promise<JSHandle>;
1749
1750 /**
1751 * Reloads the current page.
1752 * @param options The navigation parameters.
1753 */
1754 reload(options?: NavigationOptions): Promise<Response>;
1755
1756 /**
1757 * Captures a screenshot of the page.
1758 * @param options The screenshot options.
1759 */
1760 screenshot(options?: Base64ScreenShotOptions): Promise<string>;
1761 screenshot(options?: BinaryScreenShotOptions): Promise<Buffer>;
1762 screenshot(options?: ScreenshotOptions): Promise<string | Buffer>;
1763
1764 /**
1765 * Toggles bypassing page's Content-Security-Policy.
1766 * NOTE CSP bypassing happens at the moment of CSP initialization rather then evaluation.
1767 * Usually this means that page.setBypassCSP should be called before navigating to the domain.
1768 * @param enabled sets bypassing of page's Content-Security-Policy.
1769 */
1770 setBypassCSP(enabled: boolean): Promise<void>;
1771
1772 /**
1773 * Determines whether cache is enabled on the page.
1774 * @param [enabled=true] Whether or not to enable cache on the page.
1775 */
1776 setCacheEnabled(enabled?: boolean): Promise<void>;
1777
1778 /**
1779 * Sets the cookies on the page.
1780 * @param cookies The cookies to set.
1781 */
1782 setCookie(...cookies: SetCookie[]): Promise<void>;
1783
1784 /**
1785 * This setting will change the default maximum navigation time of 30 seconds for the following methods:
1786 * - `page.goto`
1787 * - `page.goBack`
1788 * - `page.goForward`
1789 * - `page.reload`
1790 * - `page.waitForNavigation`
1791 */
1792 setDefaultNavigationTimeout(timeout: number): void;
1793
1794 /**
1795 * This setting will change the default maximum time for the following methods and related shortcuts:
1796 * - `page.goBack`
1797 * - `page.goForward`
1798 * - `page.goto`
1799 * - `page.reload`
1800 * - `page.setContent`
1801 * - `page.waitFor`
1802 * - `page.waitForFunction`
1803 * - `page.waitForNavigation`
1804 * - `page.waitForRequest`
1805 * - `page.waitForResponse`
1806 * - `page.waitForSelector`
1807 * - `page.waitForXPath`
1808 *
1809 * NOTE page.setDefaultNavigationTimeout takes priority over page.setDefaultTimeout
1810 */
1811 setDefaultTimeout(timeout: number): void;
1812
1813 /**
1814 * The extra HTTP headers will be sent with every request the page initiates.
1815 * @param headers An object containing additional http headers to be sent with every request. All header values must be strings.
1816 */
1817 setExtraHTTPHeaders(headers: Headers): Promise<void>;
1818
1819 /**
1820 * Sets the page's geolocation.
1821 */
1822 setGeolocation(options: GeoOptions): Promise<void>;
1823
1824 /**
1825 * Determines whether JavaScript is enabled on the page.
1826 * @param enable Whether or not to enable JavaScript on the page.
1827 */
1828 setJavaScriptEnabled(enabled: boolean): Promise<void>;
1829
1830 /**
1831 * Determines whether the offline mode is enabled.
1832 * @param enabled When `true`, enables the offline mode for the page.
1833 */
1834 setOfflineMode(enabled: boolean): Promise<void>;
1835
1836 /**
1837 * Determines whether the request interception is enabled.
1838 * @param enabled When `true` the methods `request.abort`, `request.continue` and `request.respond` must be used.
1839 */
1840 setRequestInterception(enabled: boolean): Promise<void>;
1841
1842 /**
1843 * Specifies the User-Agent used in this page.
1844 * @param userAgent The user-agent to be used in the page.
1845 */
1846 setUserAgent(userAgent: string): Promise<void>;
1847 /**
1848 * Sets the viewport of the page.
1849 * @param viewport The viewport parameters.
1850 */
1851 setViewport(viewport: Viewport): Promise<void>;
1852
1853 /** @returns The target this page was created from */
1854 target(): Target;
1855
1856 /** Returns the page's title. */
1857 title(): Promise<string>;
1858
1859 /** Returns the virtual touchscreen object. */
1860 touchscreen: Touchscreen;
1861
1862 /** Returns the tracing object. */
1863 tracing: Tracing;
1864
1865 /**
1866 * The page's URL. This is a shortcut for `page.mainFrame().url()`
1867 */
1868 url(): string;
1869
1870 /** Gets the page viewport. */
1871 viewport(): Viewport;
1872
1873 waitForRequest(urlOrPredicate: string | ((req: Request) => boolean), options?: Timeoutable): Promise<Request>;
1874
1875 waitForResponse(urlOrPredicate: string | ((res: Response) => boolean), options?: Timeoutable): Promise<Response>;
1876
1877 /**
1878 * In non-headless Chromium, this method results in the native file picker dialog not showing up for the user.
1879 * This method is typically coupled with an action that triggers file choosing.
1880 * This must be called before the file chooser is launched. It will not return a currently active file chooser.
1881 */
1882 waitForFileChooser(options?: Timeoutable): Promise<FileChooser>;
1883
1884 /** This method returns all of the dedicated WebWorkers associated with the page. */
1885 workers(): Worker[];
1886}
1887
1888export interface TargetAwaiter {
1889 waitForTarget(predicate: (target: Target) => boolean, options?: Timeoutable): Promise<Target>;
1890}
1891
1892/** A Browser is created when Puppeteer connects to a Chromium instance, either through puppeteer.launch or puppeteer.connect. */
1893export interface Browser extends EventEmitter, TargetAwaiter {
1894 /**
1895 * Adds the listener function to the end of the listeners array for the event named `eventName`.
1896 * No checks are made to see if the listener has already been added. Multiple calls passing the same combination of
1897 * `eventName` and listener will result in the listener being added, and called, multiple times.
1898 * @param event The name of the event.
1899 * @param handler The callback function.
1900 */
1901 on<K extends keyof BrowserEventObj>(eventName: K, handler: (e: BrowserEventObj[K], ...args: any[]) => void): this;
1902
1903 /**
1904 * Adds a one time listener function for the event named `eventName`.
1905 * The next time `eventName` is triggered, this listener is removed and then invoked.
1906 * @param event The name of the event.
1907 * @param handler The callback function.
1908 */
1909 once<K extends keyof BrowserEventObj>(eventName: K, handler: (e: BrowserEventObj[K], ...args: any[]) => void): this;
1910
1911 /**
1912 * Returns an array of all open browser contexts.
1913 * In a newly created browser, this will return a single instance of BrowserContext.
1914 */
1915 browserContexts(): BrowserContext[];
1916
1917 /**
1918 * Closes browser with all the pages (if any were opened).
1919 * The browser object itself is considered to be disposed and can not be used anymore.
1920 */
1921 close(): Promise<void>;
1922
1923 /**
1924 * Creates a new incognito browser context.
1925 * This won't share cookies/cache with other browser contexts.
1926 */
1927 createIncognitoBrowserContext(): Promise<BrowserContext>;
1928
1929 /**
1930 * Disconnects Puppeteer from the browser, but leaves the Chromium process running.
1931 * After calling `disconnect`, the browser object is considered disposed and cannot be used anymore.
1932 */
1933 disconnect(): void;
1934
1935 /** Indicates that the browser is connected. */
1936 isConnected(): boolean;
1937
1938 /**
1939 * Returns the default browser context.
1940 * The default browser context can not be closed.
1941 */
1942 defaultBrowserContext(): BrowserContext;
1943
1944 /** Promise which resolves to a new Page object. */
1945 newPage(): Promise<Page>;
1946
1947 /** Promise which resolves to an array of all open pages. */
1948 pages(): Promise<Page[]>;
1949
1950 /** Spawned browser process. Returns `null` if the browser instance was created with `puppeteer.connect` method */
1951 process(): ChildProcess;
1952
1953 /** A target associated with the browser. */
1954 target(): Target;
1955
1956 /** Promise which resolves to an array of all active targets. */
1957 targets(): Promise<Target[]>;
1958
1959 /**
1960 * Promise which resolves to the browser's original user agent.
1961 * **NOTE** Pages can override browser user agent with `page.setUserAgent`.
1962 */
1963 userAgent(): Promise<string>;
1964
1965 /** For headless Chromium, this is similar to HeadlessChrome/61.0.3153.0. For non-headless, this is similar to Chrome/61.0.3153.0. */
1966 version(): Promise<string>;
1967
1968 /** Browser websocket endpoint which can be used as an argument to puppeteer.connect. The format is ws://${host}:${port}/devtools/browser/<id> */
1969 wsEndpoint(): string;
1970}
1971
1972export interface BrowserEventObj {
1973 /** Emitted when puppeteer gets disconnected from the browser instance. */
1974 disconnected: undefined;
1975
1976 /** Emitted when the url of a target changes. */
1977 targetchanged: Target;
1978
1979 /** Emitted when a target is created, for example when a new page is opened by `window.open` or `browser.newPage`. */
1980 targetcreated: Target;
1981
1982 /** Emitted when a target is destroyed, for example when a page is closed. */
1983 targetdestroyed: Target;
1984}
1985
1986export type Permission =
1987 | 'geolocation'
1988 | 'midi'
1989 | 'midi-sysex'
1990 | 'notifications'
1991 | 'push'
1992 | 'camera'
1993 | 'microphone'
1994 | 'background-sync'
1995 | 'ambient-light-sensor'
1996 | 'accelerometer'
1997 | 'gyroscope'
1998 | 'magnetometer'
1999 | 'accessibility-events'
2000 | 'clipboard-read'
2001 | 'clipboard-write'
2002 | 'payment-handler';
2003
2004/**
2005 * BrowserContexts provide a way to operate multiple independent browser sessions.
2006 * When a browser is launched, it has a single BrowserContext used by default.
2007 * The method `browser.newPage()` creates a page in the default browser context.
2008 */
2009export interface BrowserContext extends EventEmitter, TargetAwaiter {
2010 /**
2011 * Adds the listener function to the end of the listeners array for the event named `eventName`.
2012 * No checks are made to see if the listener has already been added. Multiple calls passing the same combination of
2013 * `eventName` and listener will result in the listener being added, and called, multiple times.
2014 * @param event The name of the event.
2015 * @param handler The callback function.
2016 */
2017 on<K extends keyof BrowserContextEventObj>(
2018 eventName: K,
2019 handler: (e: BrowserContextEventObj[K], ...args: any[]) => void,
2020 ): this;
2021
2022 /**
2023 * Adds a one time listener function for the event named `eventName`.
2024 * The next time `eventName` is triggered, this listener is removed and then invoked.
2025 * @param event The name of the event.
2026 * @param handler The callback function.
2027 */
2028 once<K extends keyof BrowserContextEventObj>(
2029 eventName: K,
2030 handler: (e: BrowserContextEventObj[K], ...args: any[]) => void,
2031 ): this;
2032
2033 /** The browser this browser context belongs to. */
2034 browser(): Browser;
2035
2036 /**
2037 * Clears all permission overrides for the browser context.
2038 */
2039 clearPermissionOverrides(): Promise<void>;
2040
2041 /** Closes the browser context. All the targets that belong to the browser context will be closed. */
2042 close(): Promise<void>;
2043
2044 /**
2045 * Returns whether BrowserContext is incognito.
2046 * The default browser context is the only non-incognito browser context.
2047 */
2048 isIncognito(): boolean;
2049
2050 /** Creates a new page in the browser context. */
2051 newPage(): Promise<Page>;
2052
2053 /**
2054 *
2055 * @param origin The origin to grant permissions to, e.g. "https://example.com".
2056 * @param permissions An array of permissions to grant.
2057 * All permissions that are not listed here will be automatically denied.
2058 */
2059 overridePermissions(origin: string, permissions: Permission[]): Promise<void>;
2060
2061 /** Promise which resolves to an array of all open pages. */
2062 pages(): Promise<Page[]>;
2063
2064 /** An array of all active targets inside the browser context. */
2065 targets(): Target[];
2066}
2067
2068export interface BrowserContextEventObj {
2069 /** Emitted when the url of a target inside the browser context changes. */
2070 targetchanged: Target;
2071
2072 /** Emitted when a target is created, for example when a new page is opened by `window.open` or `browserContext.newPage`. */
2073 targetcreated: Target;
2074
2075 /** Emitted when a target is destroyed, for example when a page is closed. */
2076 targetdestroyed: Target;
2077}
2078
2079export type TargetType = 'page' | 'background_page' | 'shared_worker' | 'service_worker' | 'browser' | 'other';
2080
2081export interface Target {
2082 /** Get the browser the target belongs to. */
2083 browser(): Browser;
2084
2085 /** The browser context the target belongs to. */
2086 browserContext(): BrowserContext;
2087
2088 /** Creates a Chrome Devtools Protocol session attached to the target. */
2089 createCDPSession(): Promise<CDPSession>;
2090
2091 /** Get the target that opened this target. Top-level targets return `null`. */
2092 opener(): Target | null;
2093
2094 /** Returns the target `Page` or a `null` if the type of the page is not "page". */
2095 page(): Promise<Page>;
2096
2097 /** Identifies what kind of target this is. */
2098 type(): TargetType;
2099
2100 /** Returns the target URL. */
2101 url(): string;
2102
2103 /** If the target is not of type `service_worker` or `shared_worker`, resolves `null`. */
2104 worker(): Promise<Worker | null>;
2105}
2106
2107export interface LaunchOptions extends ChromeArgOptions, BrowserOptions, Timeoutable {
2108 /**
2109 * Which browser to launch.
2110 * At this time, this is either `chrome` or `firefox`. See also `PUPPETEER_PRODUCT`.
2111 * @default 'chrome'
2112 */
2113 product?: Product;
2114 /**
2115 * Path to a Chromium executable to run instead of bundled Chromium. If
2116 * executablePath is a relative path, then it is resolved relative to current
2117 * working directory.
2118 */
2119 executablePath?: string;
2120 /**
2121 * Do not use `puppeteer.defaultArgs()` for launching Chromium.
2122 * @default false
2123 */
2124 ignoreDefaultArgs?: boolean | string[];
2125 /**
2126 * Close chrome process on Ctrl-C.
2127 * @default true
2128 */
2129 handleSIGINT?: boolean;
2130 /**
2131 * Close chrome process on SIGTERM.
2132 * @default true
2133 */
2134 handleSIGTERM?: boolean;
2135 /**
2136 * Close chrome process on SIGHUP.
2137 * @default true
2138 */
2139 handleSIGHUP?: boolean;
2140 /**
2141 * Whether to pipe browser process stdout and stderr into process.stdout and
2142 * process.stderr.
2143 * @default false
2144 */
2145 dumpio?: boolean;
2146 /**
2147 * Specify environment variables that will be visible to Chromium.
2148 * @default `process.env`.
2149 */
2150 env?: {
2151 [key: string]: string | boolean | number;
2152 };
2153 /**
2154 * Connects to the browser over a pipe instead of a WebSocket.
2155 * @default false
2156 */
2157 pipe?: boolean;
2158}
2159
2160export interface ChromeArgOptions {
2161 /**
2162 * Whether to run browser in headless mode.
2163 * @default true unless the devtools option is true.
2164 */
2165 headless?: boolean;
2166 /**
2167 * Additional arguments to pass to the browser instance.
2168 * The list of Chromium flags can be found here.
2169 */
2170 args?: string[];
2171 /**
2172 * Path to a User Data Directory.
2173 */
2174 userDataDir?: string;
2175 /**
2176 * Whether to auto-open a DevTools panel for each tab.
2177 * If this option is true, the headless option will be set false.
2178 */
2179 devtools?: boolean;
2180}
2181
2182export interface BrowserOptions {
2183 /**
2184 * Whether to ignore HTTPS errors during navigation.
2185 * @default false
2186 */
2187 ignoreHTTPSErrors?: boolean;
2188 /**
2189 * Sets a consistent viewport for each page. Defaults to an 800x600 viewport. null disables the default viewport.
2190 */
2191 defaultViewport?: {
2192 /**
2193 * page width in pixels.
2194 */
2195 width?: number;
2196 /**
2197 * page height in pixels.
2198 */
2199 height?: number;
2200 /**
2201 * Specify device scale factor (can be thought of as dpr).
2202 * @default 1
2203 */
2204 deviceScaleFactor?: number;
2205 /**
2206 * Whether the meta viewport tag is taken into account.
2207 * @default false
2208 */
2209 isMobile?: boolean;
2210 /**
2211 * Specifies if viewport supports touch events.
2212 * @default false
2213 */
2214 hasTouch?: boolean;
2215 /**
2216 * Specifies if viewport is in landscape mode.
2217 * @default false
2218 */
2219 isLandscape?: boolean;
2220 } | null;
2221 /**
2222 * Slows down Puppeteer operations by the specified amount of milliseconds.
2223 * Useful so that you can see what is going on.
2224 */
2225 slowMo?: number;
2226}
2227
2228export interface ConnectOptions extends BrowserOptions {
2229 /**
2230 * A browser url to connect to, in format `http://${host}:${port}`.
2231 * Use interchangeably with browserWSEndpoint to let Puppeteer fetch it from metadata endpoint.
2232 */
2233 browserURL?: string;
2234
2235 /** A browser websocket endpoint to connect to. */
2236 browserWSEndpoint?: string;
2237
2238 /**
2239 * **Experimental** Specify a custom transport object for Puppeteer to use.
2240 */
2241 transport?: ConnectionTransport;
2242}
2243
2244export interface ConnectionTransport {
2245 send(message: string): void;
2246 close(): void;
2247 onmessage?(message: string): void;
2248 onclose?(): void;
2249}
2250
2251export interface CDPSession extends EventEmitter {
2252 /**
2253 * Detaches session from target. Once detached, session won't emit any events and can't be used
2254 * to send messages.
2255 */
2256 detach(): Promise<void>;
2257
2258 /**
2259 * @param method Protocol method name
2260 */
2261 send(method: string, params?: object): Promise<object>;
2262}
2263
2264export interface Coverage {
2265 startCSSCoverage(options?: StartCoverageOptions): Promise<void>;
2266 startJSCoverage(options?: StartCoverageOptions): Promise<void>;
2267 stopCSSCoverage(): Promise<CoverageEntry[]>;
2268 stopJSCoverage(): Promise<CoverageEntry[]>;
2269}
2270
2271export interface StartCoverageOptions {
2272 /**
2273 * Whether to reset coverage on every navigation.
2274 * @default true
2275 */
2276 resetOnNavigation?: boolean;
2277 /**
2278 * Whether anonymous scripts generated by the page should be reported.
2279 * @default false
2280 */
2281 reportAnonymousScripts?: boolean;
2282}
2283
2284export interface CoverageEntry {
2285 url: string;
2286 text: string;
2287 ranges: Array<{ start: number; end: number }>;
2288}
2289
2290/** BrowserFetcher can download and manage different versions of Chromium. */
2291export interface BrowserFetcher {
2292 /** The method initiates a HEAD request to check if the revision is available. */
2293 canDownload(revision: string): Promise<boolean>;
2294 /** The method initiates a GET request to download the revision from the host. */
2295 download(
2296 revision: string,
2297 progressCallback?: (downloadBytes: number, totalBytes: number) => void,
2298 ): Promise<RevisionInfo>;
2299 localRevisions(): Promise<string[]>;
2300 platform(): Platform;
2301 product(): Product;
2302 remove(revision: string): Promise<void>;
2303 revisionInfo(revision: string): RevisionInfo;
2304}
2305
2306export interface RevisionInfo {
2307 /** The revision the info was created from */
2308 revision: string;
2309 /** Path to the extracted revision folder */
2310 folderPath: string;
2311 /** Path to the revision executable */
2312 executablePath: string;
2313 /** URL this revision can be downloaded from */
2314 url: string;
2315 /** whether the revision is locally available on disk */
2316 local: boolean;
2317 product: Product;
2318}
2319
2320export interface FetcherOptions {
2321 /** A download host to be used. Defaults to `https://storage.googleapis.com`. */
2322 host?: string;
2323 /** A path for the downloads folder. Defaults to `<root>/.local-chromium`, where `<root>` is puppeteer's package root. */
2324 path?: string;
2325 /** Possible values are: `mac`, `win32`, `win64`, `linux`. Defaults to the current platform. */
2326 platform?: Platform;
2327 /**
2328 * @default 'chrome'
2329 */
2330 product?: Product;
2331}
2332
2333type EventType = string | symbol;
2334type Handler<T = any> = (event?: T) => void;
2335
2336export interface EventEmitter {
2337 on(event: EventType, handler: Handler): EventEmitter;
2338 off(event: EventType, handler: Handler): EventEmitter;
2339 addListener(event: EventType, handler: Handler): EventEmitter;
2340 removeListener(event: EventType, handler: Handler): EventEmitter;
2341 emit(event: EventType, eventData?: any): boolean;
2342 once(event: EventType, handler: Handler): EventEmitter;
2343 listenerCount(event: string): number;
2344 removeAllListeners(event?: EventType): EventEmitter;
2345}
2346
2347/**
2348 * Contains two functions `queryOne` and `queryAll` that can
2349 * be {@link Puppeteer.registerCustomQueryHandler | registered}
2350 * as alternative querying strategies. The functions `queryOne` and `queryAll`
2351 * are executed in the page context. `queryOne` should take an `Element` and a
2352 * selector string as argument and return a single `Element` or `null` if no
2353 * element is found. `queryAll` takes the same arguments but should instead
2354 * return a `NodeListOf<Element>` or `Array<Element>` with all the elements
2355 * that match the given query selector.
2356 */
2357export interface CustomQueryHandler {
2358 queryOne?: (element: Element | Document, selector: string) => Element | null;
2359 queryAll?: (element: Element | Document, selector: string) => Element[] | NodeListOf<Element>;
2360}
2361
2362/** Attaches Puppeteer to an existing Chromium instance */
2363export function connect(options?: ConnectOptions): Promise<Browser>;
2364/** The default flags that Chromium will be launched with */
2365export function defaultArgs(options?: ChromeArgOptions): string[];
2366/** Path where Puppeteer expects to find bundled Chromium */
2367export function executablePath(): string;
2368/** The method launches a browser instance with given arguments. The browser will be closed when the parent node.js process is closed. */
2369export function launch(options?: LaunchOptions): Promise<Browser>;
2370/** This methods attaches Puppeteer to an existing Chromium instance. */
2371export function createBrowserFetcher(options?: FetcherOptions): BrowserFetcher;
2372
2373/**
2374 * The name of the browser that is under automation (`"chrome"` or `"firefox"`)
2375 *
2376 * The product is set by the `PUPPETEER_PRODUCT` environment variable or the `product`
2377 * option in `puppeteer.launch([options])` and defaults to `chrome`.
2378 * Firefox support is experimental.
2379 */
2380export const product: Product;
2381
2382/**
2383 * Registers a {@link CustomQueryHandler | custom query handler}. After
2384 * registration, the handler can be used everywhere where a selector is
2385 * expected by prepending the selection string with `<name>/`. The name is
2386 * only allowed to consist of lower- and upper case latin letters.
2387 * @example
2388 * ```
2389 * puppeteer.registerCustomQueryHandler('text', { … });
2390 * const aHandle = await page.$('text/…');
2391 * ```
2392 * @param name - The name that the custom query handler will be registered under.
2393 * @param queryHandler - The {@link CustomQueryHandler | custom query handler} to
2394 * register.
2395 */
2396export function registerCustomQueryHandler(name: string, queryHandler: CustomQueryHandler): void;
2397/**
2398 * @param name - The name of the query handler to unregistered.
2399 */
2400export function unregisterCustomQueryHandler(name: string): void;
2401/**
2402 * @returns a list with the names of all registered custom query handlers.
2403 */
2404export function customQueryHandlerNames(): string[];
2405/**
2406 * Clears all registered handlers.
2407 */
2408export function clearCustomQueryHandlers(): void;
2409
2410// Shut off automatic exporting. See: https://github.com/Microsoft/dtslint/blob/master/docs/strict-export-declare-modifiers.md
2411export {};
2412
\No newline at end of file