UNPKG

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