// Type definitions for puppeteer 5.4 // Project: https://github.com/GoogleChrome/puppeteer#readme // Definitions by: Marvin Hagemeister // Christopher Deutsch // Konstantin Simon Maria Möllers // Simon Schick // Serban Ghita // Jason Kaczmarsky // Dave Cardwell // Andrés Ortiz // Piotr Błażejewicz // Cameron Hunter // Pirasis Leelatanon // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 3.0 /// import { ChildProcess } from 'child_process'; export namespace devices { interface Device { name: string; userAgent: string; viewport: { width: number; height: number; deviceScaleFactor: number; isMobile: boolean; hasTouch: boolean; isLandscape: boolean; }; } } export const devices: { [name: string]: devices.Device }; declare class CustomError extends Error { constructor(message: string); } /** * TimeoutError is emitted whenever certain operations are terminated due to timeout. * * Example operations are {@link Page.waitForSelector | page.waitForSelector} * or {@link PuppeteerNode.launch | puppeteer.launch}. */ declare class TimeoutError extends CustomError {} export namespace errors { class TimeoutError extends CustomError {} } /** Wraps a DOM element into an ElementHandle instance */ export type WrapElementHandle = X extends Element ? ElementHandle : X; /** Unwraps a DOM element out of an ElementHandle instance */ export type UnwrapElementHandle = X extends ElementHandle ? E : X; export type Serializable = number | string | boolean | null | JSONArray | JSONObject; export interface JSONArray extends Array {} export interface JSONObject { [key: string]: Serializable; } export type SerializableOrJSHandle = Serializable | JSHandle; /** * We want to maintain intellisense for known values but remain open to unknown values. This type is a workaround for * [Microsoft/TypeScript#29729](https://github.com/Microsoft/TypeScript/issues/29729). It will be removed as soon as * it's not needed anymore. */ type LiteralUnion = LiteralType | (string & { _?: never | undefined }); export type Platform = LiteralUnion<'mac' | 'win32' | 'win64' | 'linux'>; export type Product = LiteralUnion<'chrome' | 'firefox'>; /** Defines `$eval` and `$$eval` for Page, Frame and ElementHandle. */ export interface Evalable { /** * This method runs `document.querySelector` within the context and passes it as the first argument to `pageFunction`. * If there's no element matching `selector`, the method throws an error. * * If `pageFunction` returns a Promise, then `$eval` would wait for the promise to resolve and return its value. * * @param selector A selector to query for * @param pageFunction Function to be evaluated in browser context * @returns Promise which resolves to the return value of pageFunction */ $eval(selector: string, pageFunction: (element: Element) => R | Promise): Promise>; /** * This method runs `document.querySelector` within the context and passes it as the first argument to `pageFunction`. * If there's no element matching `selector`, the method throws an error. * * If `pageFunction` returns a Promise, then `$eval` would wait for the promise to resolve and return its value. * * @param selector A selector to query for * @param pageFunction Function to be evaluated in browser context * @param x1 First argument to pass to pageFunction * @returns Promise which resolves to the return value of pageFunction */ $eval( selector: string, pageFunction: (element: Element, x1: UnwrapElementHandle) => R | Promise, x1: X1, ): Promise>; /** * This method runs `document.querySelector` within the context and passes it as the first argument to `pageFunction`. * If there's no element matching `selector`, the method throws an error. * * If `pageFunction` returns a Promise, then `$eval` would wait for the promise to resolve and return its value. * * @param selector A selector to query for * @param pageFunction Function to be evaluated in browser context * @param x1 First argument to pass to pageFunction * @param x2 Second argument to pass to pageFunction * @returns Promise which resolves to the return value of pageFunction */ $eval( selector: string, pageFunction: (element: Element, x1: UnwrapElementHandle, x2: UnwrapElementHandle) => R | Promise, x1: X1, x2: X2, ): Promise>; /** * This method runs `document.querySelector` within the context and passes it as the first argument to `pageFunction`. * If there's no element matching `selector`, the method throws an error. * * If `pageFunction` returns a Promise, then `$eval` would wait for the promise to resolve and return its value. * * @param selector A selector to query for * @param pageFunction Function to be evaluated in browser context * @param x1 First argument to pass to pageFunction * @param x2 Second argument to pass to pageFunction * @param x3 Third argument to pass to pageFunction * @returns Promise which resolves to the return value of pageFunction */ $eval( selector: string, pageFunction: ( element: Element, x1: UnwrapElementHandle, x2: UnwrapElementHandle, x3: UnwrapElementHandle, ) => R | Promise, x1: X1, x2: X2, x3: X3, ): Promise>; /** * This method runs `document.querySelector` within the context and passes it as the first argument to `pageFunction`. * If there's no element matching `selector`, the method throws an error. * * If `pageFunction` returns a Promise, then `$eval` would wait for the promise to resolve and return its value. * * @param selector A selector to query for * @param pageFunction Function to be evaluated in browser context * @param args Arguments to pass to pageFunction * @returns Promise which resolves to the return value of pageFunction */ $eval( selector: string, pageFunction: (element: Element, ...args: any[]) => R | Promise, ...args: SerializableOrJSHandle[] ): Promise>; /** * This method runs `Array.from(document.querySelectorAll(selector))` within the context and passes it as the * first argument to `pageFunction`. * * If `pageFunction` returns a Promise, then `$$eval` would wait for the promise to resolve and return its value. * * @param selector A selector to query for * @param pageFunction Function to be evaluated in browser context * @returns Promise which resolves to the return value of pageFunction */ $$eval(selector: string, pageFunction: (elements: Element[]) => R | Promise): Promise>; /** * This method runs `Array.from(document.querySelectorAll(selector))` within the context and passes it as the * first argument to `pageFunction`. * * If `pageFunction` returns a Promise, then `$$eval` would wait for the promise to resolve and return its value. * * @param selector A selector to query for * @param pageFunction Function to be evaluated in browser context * @param x1 First argument to pass to pageFunction * @returns Promise which resolves to the return value of pageFunction */ $$eval( selector: string, pageFunction: (elements: Element[], x1: UnwrapElementHandle) => R | Promise, x1: X1, ): Promise>; /** * This method runs `Array.from(document.querySelectorAll(selector))` within the context and passes it as the * first argument to `pageFunction`. * * If `pageFunction` returns a Promise, then `$$eval` would wait for the promise to resolve and return its value. * * @param selector A selector to query for * @param pageFunction Function to be evaluated in browser context * @param x1 First argument to pass to pageFunction * @param x2 Second argument to pass to pageFunction * @returns Promise which resolves to the return value of pageFunction */ $$eval( selector: string, pageFunction: (elements: Element[], x1: UnwrapElementHandle, x2: UnwrapElementHandle) => R | Promise, x1: X1, x2: X2, ): Promise>; /** * This method runs `Array.from(document.querySelectorAll(selector))` within the context and passes it as the * first argument to `pageFunction`. * * If `pageFunction` returns a Promise, then `$$eval` would wait for the promise to resolve and return its value. * * @param selector A selector to query for * @param pageFunction Function to be evaluated in browser context * @param x1 First argument to pass to pageFunction * @param x2 Second argument to pass to pageFunction * @param x3 Third argument to pass to pageFunction * @returns Promise which resolves to the return value of pageFunction */ $$eval( selector: string, pageFunction: ( elements: Element[], x1: UnwrapElementHandle, x2: UnwrapElementHandle, x3: UnwrapElementHandle, ) => R | Promise, x1: X1, x2: X2, x3: X3, ): Promise>; /** * This method runs `Array.from(document.querySelectorAll(selector))` within the context and passes it as the * first argument to `pageFunction`. * * If `pageFunction` returns a Promise, then `$$eval` would wait for the promise to resolve and return its value. * * @param selector A selector to query for * @param pageFunction Function to be evaluated in browser context * @param args Arguments to pass to pageFunction * @returns Promise which resolves to the return value of pageFunction */ $$eval( selector: string, pageFunction: (elements: Element[], ...args: any[]) => R | Promise, ...args: SerializableOrJSHandle[] ): Promise>; } export interface JSEvalable { /** * Evaluates a function in the browser context. * 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. * If the function passed into frame.evaluate returns a non-Serializable value, then frame.evaluate resolves to undefined. * @param fn Function to be evaluated in browser context * @param args Arguments to pass to `fn` */ evaluate>( pageFunction: T, ...args: SerializableOrJSHandle[] ): Promise extends PromiseLike ? U : EvaluateFnReturnType>; /** * The only difference between `evaluate` and `evaluateHandle` is that `evaluateHandle` returns in-page object (`JSHandle`). * If the function, passed to the `evaluateHandle`, returns a `Promise`, then `evaluateHandle` would wait for the * promise to resolve and return its value. * The TypeScript definitions assume that `evaluateHandle` returns a `JSHandle`, but if you know it's going to return an * `ElementHandle`, pass it as the generic argument: * @param pageFunction - a function that is run within the page * @param args - arguments to be passed to the pageFunction */ // tslint:disable-next-line no-unnecessary-generics (This generic is meant to be passed explicitly.) # https://github.com/Microsoft/dtslint/issues/76 evaluateHandle( pageFunction: string | ((arg1: A, ...args: any[]) => any), ...args: SerializableOrJSHandle[] // tslint:disable-next-line no-unnecessary-generics (This generic is meant to be passed explicitly.) # https://github.com/Microsoft/dtslint/issues/76 ): Promise; } /** Keyboard provides an api for managing a virtual keyboard. */ export interface Keyboard { /** * Dispatches a keydown event. * @param key Name of key to press, such as ArrowLeft. * @param options Specifies a input text event. */ down(key: string, options?: { text?: string | undefined }): Promise; /** Shortcut for `keyboard.down` and `keyboard.up`. */ press(key: string, options?: { text?: string | undefined; delay?: number | undefined }): Promise; /** Dispatches a `keypress` and `input` event. This does not send a `keydown` or keyup `event`. */ sendCharacter(char: string): Promise; /** * Sends a keydown, keypress/input, and keyup event for each character in the text. * @param text A text to type into a focused element. * @param options Specifies the typing options. */ type(text: string, options?: { delay?: number | undefined }): Promise; /** * Dispatches a keyup event. * @param key Name of key to release, such as ArrowLeft. */ up(key: string): Promise; } export interface MousePressOptions { /** * left, right, or middle. * @default left */ button?: MouseButtons | undefined; /** * The number of clicks. * @default 1 */ clickCount?: number | undefined; } export interface MouseWheelOptions { deltaX?: number | undefined; deltaY?: number | undefined; } export interface MouseWheelOptions { /** * X delta in CSS pixels for mouse wheel event. Positive values emulate a scroll up and negative values a scroll down event. * @default 0 */ deltaX?: number | undefined; /** * Y delta in CSS pixels for mouse wheel event. Positive values emulate a scroll right and negative values a scroll left event. * @default 0 */ deltaY?: number | undefined; } export interface Mouse { /** * Shortcut for `mouse.move`, `mouse.down` and `mouse.up`. * @param x The x position. * @param y The y position. * @param options The click options. */ click(x: number, y: number, options?: ClickOptions): Promise; /** * Dispatches a `mousedown` event. * @param options The mouse press options. */ down(options?: MousePressOptions): Promise; /** * Dispatches a `mousemove` event. * @param x The x position. * @param y The y position. * @param options The mouse move options. */ move(x: number, y: number, options?: { steps: number }): Promise; /** * Dispatches a `mouseup` event. * @param options The mouse press options. */ up(options?: MousePressOptions): Promise; /** * Dispatches a `mousewheel` event. * @param options - Optional: `MouseWheelOptions`. * * @example * An example of zooming into an element: * ```js * await page.goto('https://mdn.mozillademos.org/en-US/docs/Web/API/Element/wheel_event$samples/Scaling_an_element_via_the_wheel?revision=1587366'); * * const elem = await page.$('div'); * const boundingBox = await elem.boundingBox(); * await page.mouse.move( * boundingBox.x + boundingBox.width / 2, * boundingBox.y + boundingBox.height / 2 * ); * * await page.mouse.wheel({ deltaY: -100 }) * ``` */ wheel(options?: MouseWheelOptions): Promise; } export interface Touchscreen { /** * Dispatches a touchstart and touchend event. * @param x The x position. * @param y The y position. */ tap(x: number, y: number): Promise; } /** * You can use `tracing.start` and `tracing.stop` to create a trace file which can be opened in Chrome DevTools or timeline viewer. */ export interface Tracing { start(options: TracingStartOptions): Promise; stop(): Promise; } export interface TracingStartOptions { path?: string | undefined; screenshots?: boolean | undefined; categories?: string[] | undefined; } export type DialogType = 'alert' | 'beforeunload' | 'confirm' | 'prompt'; /** Dialog objects are dispatched by page via the 'dialog' event. */ export interface Dialog { /** * Accepts the dialog. * @param promptText A text to enter in prompt. Does not cause any effects if the dialog's type is not prompt. */ accept(promptText?: string): Promise; /** If dialog is prompt, returns default prompt value. Otherwise, returns empty string. */ defaultValue(): string; /** Dismiss the dialog */ dismiss(): Promise; /** Returns the message displayed in the dialog. */ message(): string; /** The dialog type. Dialog's type, can be one of `alert`, `beforeunload`, `confirm` or `prompt`. */ type(): DialogType; } export type ConsoleMessageType = | 'log' | 'debug' | 'info' | 'error' | 'warning' | 'dir' | 'dirxml' | 'table' | 'trace' | 'clear' | 'startGroup' | 'startGroupCollapsed' | 'endGroup' | 'assert' | 'profile' | 'profileEnd' | 'count' | 'timeEnd'; export interface ConsoleMessageLocation { /** * URL of the resource if known. */ url?: string | undefined; /** * Line number in the resource if known */ lineNumber?: number | undefined; /** * Column number in the resource if known. */ columnNumber?: number | undefined; } /** ConsoleMessage objects are dispatched by page via the 'console' event. */ export interface ConsoleMessage { /** The message arguments. */ args(): JSHandle[]; /** The location the message originated from */ location(): ConsoleMessageLocation; /** The message text. */ text(): string; type(): ConsoleMessageType; } export interface AuthOptions { username: string; password: string; } export type MouseButtons = 'left' | 'right' | 'middle'; export interface ClickOptions { /** @default MouseButtons.Left */ button?: MouseButtons | undefined; /** @default 1 */ clickCount?: number | undefined; /** * Time to wait between mousedown and mouseup in milliseconds. * @default 0 */ delay?: number | undefined; } export type SameSiteSetting = 'Strict' | 'Lax'; /** Represents a browser cookie. */ export interface Cookie { /** The cookie name. */ name: string; /** The cookie value. */ value: string; /** The cookie domain. */ domain: string; /** The cookie path. */ path: string; /** The cookie Unix expiration time in seconds. */ expires: number; /** The cookie size */ size: number; /** The cookie http only flag. */ httpOnly: boolean; /** The session cookie flag. */ session: boolean; /** The cookie secure flag. */ secure: boolean; /** The cookie same site definition. */ sameSite: SameSiteSetting; } export interface DeleteCookie { /** The cookie name. */ name: string; url?: string | undefined; domain?: string | undefined; path?: string | undefined; } export interface SetCookie { /** The cookie name. */ name: string; /** The cookie value. */ value: string; /** 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. */ url?: string | undefined; /** The cookie domain. */ domain?: string | undefined; /** The cookie path. */ path?: string | undefined; /** The cookie Unix expiration time in seconds. */ expires?: number | undefined; /** The cookie http only flag. */ httpOnly?: boolean | undefined; /** The session cookie flag. */ session?: boolean | undefined; /** The cookie secure flag. */ secure?: boolean | undefined; /** The cookie same site definition. */ sameSite?: SameSiteSetting | undefined; } export interface Viewport { /** The page width in pixels. */ width: number; /** The page height in pixels. */ height: number; /** * Specify device scale factor (can be thought of as dpr). * @default 1 */ deviceScaleFactor?: number | undefined; /** * Whether the `meta viewport` tag is taken into account. * @default false */ isMobile?: boolean | undefined; /** * Specifies if viewport supports touch events. * @default false */ hasTouch?: boolean | undefined; /** * Specifies if viewport is in landscape mode. * @default false */ isLandscape?: boolean | undefined; } /** Page emulation options. */ export interface EmulateOptions { /** The viewport emulation options. */ viewport: Viewport; /** The emulated user-agent. */ userAgent: string; } export type EvaluateFn = string | ((arg1: T, ...args: any[]) => any); export type EvaluateFnReturnType = T extends (...args: any[]) => infer R ? R : unknown; export type LoadEvent = 'load' | 'domcontentloaded' | 'networkidle0' | 'networkidle2'; export interface Timeoutable { /** * Maximum navigation time in milliseconds, pass 0 to disable timeout. * @default 30000 */ timeout?: number | undefined; } /** The navigation options. */ export interface NavigationOptions extends Timeoutable { /** * When to consider navigation succeeded. * @default load Navigation is consider when the `load` event is fired. */ waitUntil?: LoadEvent | LoadEvent[] | undefined; } /** * Navigation options for `page.goto`. */ export interface DirectNavigationOptions extends NavigationOptions { /** * Referer header value. * If provided it will take preference over the referer header value set by * [page.setExtraHTTPHeaders()](#pagesetextrahttpheadersheaders). */ referer?: string | undefined; } /** Accepts values labeled with units. If number, treat as pixels. */ export type LayoutDimension = string | number; export type PDFFormat = 'Letter' | 'Legal' | 'Tabloid' | 'Ledger' | 'A0' | 'A1' | 'A2' | 'A3' | 'A4' | 'A5' | 'A6'; export interface PDFOptions { /** * The file path to save the PDF to. * If `path` is a relative path, then it is resolved relative to current working directory. * If no path is provided, the PDF won't be saved to the disk. */ path?: string | undefined; /** * Scale of the webpage rendering. * @default 1 */ scale?: number | undefined; /** * Display header and footer. * @default false */ displayHeaderFooter?: boolean | undefined; /** * HTML template for the print header. Should be valid HTML markup with following classes used to inject printing values into them: * - `date` formatted print date * - `title` document title * - `url` document location * - `pageNumber` current page number * - `totalPages` total pages in the document */ headerTemplate?: string | undefined; /** * HTML template for the print footer. Should be valid HTML markup with following classes used to inject printing values into them: * - `date` formatted print date * - `title` document title * - `url` document location * - `pageNumber` current page number * - `totalPages` total pages in the document */ footerTemplate?: string | undefined; /** * Print background graphics. * @default false */ printBackground?: boolean | undefined; /** * Paper orientation. * @default false */ landscape?: boolean | undefined; /** * Paper ranges to print, e.g., '1-5, 8, 11-13'. * @default '' which means print all pages. */ pageRanges?: string | undefined; /** * Paper format. If set, takes priority over width or height options. * @default 'Letter' */ format?: PDFFormat | undefined; /** Paper width. */ width?: LayoutDimension | undefined; /** Paper height. */ height?: LayoutDimension | undefined; /** Paper margins, defaults to none. */ margin?: { /** Top margin. */ top?: LayoutDimension | undefined; /** Right margin. */ right?: LayoutDimension | undefined; /** Bottom margin. */ bottom?: LayoutDimension | undefined; /** Left margin. */ left?: LayoutDimension | undefined; } | undefined; /** * Give any CSS @page size declared in the page priority over what is declared in width and * height or format options. * @default false which will scale the content to fit the paper size. */ preferCSSPageSize?: boolean | undefined; } /** Defines the screenshot options. */ export interface ScreenshotOptions { /** * The file path to save the image to. The screenshot type will be inferred from file extension. * If `path` is a relative path, then it is resolved relative to current working directory. * If no path is provided, the image won't be saved to the disk. */ path?: string | undefined; /** * The screenshot type. * @default png */ type?: 'jpeg' | 'png' | undefined; /** The quality of the image, between 0-100. Not applicable to png images. */ quality?: number | undefined; /** * When true, takes a screenshot of the full scrollable page. * @default false */ fullPage?: boolean | undefined; /** * An object which specifies clipping region of the page. */ clip?: BoundingBox | undefined; /** * Hides default white background and allows capturing screenshots with transparency. * @default false */ omitBackground?: boolean | undefined; /** * The encoding of the image, can be either base64 or binary. * @default binary */ encoding?: 'base64' | 'binary' | undefined; } export interface BinaryScreenShotOptions extends ScreenshotOptions { encoding?: 'binary' | undefined; } export interface Base64ScreenShotOptions extends ScreenshotOptions { encoding: 'base64'; } /** Options for `addStyleTag` */ export interface StyleTagOptions { /** Url of the tag. */ url?: string | undefined; /** 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. */ path?: string | undefined; /** Raw CSS content to be injected into frame. */ content?: string | undefined; } /** Options for `addScriptTag` */ export interface ScriptTagOptions { /** Url of a script to be added. */ url?: string | undefined; /** 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. */ path?: string | undefined; /** Raw JavaScript content to be injected into frame. */ content?: string | undefined; /** Script type. Use 'module' in order to load a Javascript ES6 module. */ type?: string | undefined; } export interface PageFnOptions extends Timeoutable { polling?: 'raf' | 'mutation' | number | undefined; } export interface BoundingBox { /** The x-coordinate of top-left corner. */ x: number; /** The y-coordinate of top-left corner. */ y: number; /** The width. */ width: number; /** The height. */ height: number; } export interface BoxModel { /** Content box, represented as an array of {x, y} points. */ content: Box[]; /** Padding box, represented as an array of {x, y} points. */ padding: Box[]; /** Border box, represented as an array of {x, y} points. */ border: Box[]; /** Margin box, represented as an array of {x, y} points. */ margin: Box[]; width: number; height: number; } export interface Box { x: number; y: number; } /** * The Worker class represents a WebWorker. * The events workercreated and workerdestroyed are emitted on the page object to signal the worker lifecycle. */ export interface Worker extends JSEvalable { executionContext(): Promise; url(): string; } /** * Represents an in-page DOM element. ElementHandles can be created with the page.$ method. */ export interface ElementHandle extends JSHandle, Evalable { /** * The method runs element.querySelector within the page. * If no element matches the selector, the return value resolve to null. * @param selector A selector to query element for * @since 0.13.0 */ $(selector: string): Promise; /** * The method runs element.querySelectorAll within the page. * If no elements match the selector, the return value resolve to []. * @param selector A selector to query element for * @since 0.13.0 */ $$(selector: string): Promise; /** * @param selector XPath expression to evaluate. */ $x(expression: string): Promise; /** * 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. */ boundingBox(): Promise; /** * This method returns boxes of the element, or null if the element is not visible. * Boxes are represented as an array of points; each Point is an object {x, y}. Box points are sorted clock-wise. */ boxModel(): Promise; /** * This method scrolls element into view if needed, and then uses page.mouse to click in the center of the element. * If the element is detached from DOM, the method throws an error. * @param options Specifies the options. * @since 0.9.0 */ click(options?: ClickOptions): Promise; /** * @returns Resolves to the content frame for element handles referencing iframe nodes, or null otherwise. * @since 1.2.0 */ contentFrame(): Promise; /** * Calls focus on the element. */ focus(): Promise; /** * This method scrolls element into view if needed, and then uses page.mouse to hover over the center of the element. * If the element is detached from DOM, the method throws an error. */ hover(): Promise; /** * Resolves to true if the element is visible in the current viewport. */ isIntersectingViewport(): Promise; /** * Focuses the element, and then uses keyboard.down and keyboard.up. * @param key Name of key to press, such as ArrowLeft. See USKeyboardLayout for a list of all key names. * @param options The text and delay options. */ press(key: string, options?: { text?: string | undefined; delay?: number | undefined }): Promise; /** * This method scrolls element into view if needed, and then uses page.screenshot to take a screenshot of the element. * If the element is detached from DOM, the method throws an error. * @param options Same options as in page.screenshot. */ screenshot(options?: Base64ScreenShotOptions): Promise; screenshot(options?: BinaryScreenShotOptions): Promise; screenshot(options?: ScreenshotOptions): Promise; /** * Triggers a change and input event once all the provided options have been selected. If there's no has the multiple attribute, all values are considered, otherwise only the first one is taken into account. * @returns An array of option values that have been successfully selected. * @since 1.12.0 */ select(...values: string[]): Promise; /** * This method scrolls element into view if needed, and then uses touchscreen.tap to tap in the center of the element. * If the element is detached from DOM, the method throws an error. */ tap(): Promise; toString(): string; /** * Focuses the element, and then sends a keydown, keypress/input, and keyup event for each character in the text. * @param text A text to type into a focused element. * @param options The typing options. */ type(text: string, options?: { delay: number }): Promise; /** * This method expects elementHandle to point to an input element. * @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. */ uploadFile(...filePaths: string[]): Promise; } /** The class represents a context for JavaScript execution. */ export interface ExecutionContext extends JSEvalable { queryObjects(prototypeHandle: JSHandle): Promise; } /** JSHandle represents an in-page JavaScript object. */ export interface JSHandle extends JSEvalable { /** * Returns a ElementHandle */ asElement(): ElementHandle | null; /** * Stops referencing the element handle. */ dispose(): Promise; /** * Gets the execution context. */ executionContext(): ExecutionContext; /** * Returns a map with property names as keys and JSHandle instances for the property values. */ getProperties(): Promise>; /** * Fetches a single property from the objectHandle. * @param propertyName The property to get. */ getProperty(propertyName: string): Promise; /** * Returns a JSON representation of the object. * The JSON is generated by running JSON.stringify on the object in page and consequent JSON.parse in puppeteer. * @throws The method will throw if the referenced object is not stringifiable. */ jsonValue(): Promise; } export interface Metrics { /** The timestamp when the metrics sample was taken. */ Timestamp: number; /** Number of documents in the page. */ Documents: number; /** Number of frames in the page. */ Frames: number; /** Number of events in the page. */ JSEventListeners: number; /** Number of DOM nodes in the page. */ Nodes: number; /** Total number of full or partial page layout. */ LayoutCount: number; /** Total number of page style recalculations. */ RecalcStyleCount: number; /** Combined durations of all page layouts. */ LayoutDuration: number; /** Combined duration of all page style recalculations. */ RecalcStyleDuration: number; /** Combined duration of JavaScript execution. */ ScriptDuration: number; /** Combined duration of all tasks performed by the browser. */ TaskDuration: number; /** Used JavaScript heap size. */ JSHeapUsedSize: number; /** Total JavaScript heap size. */ JSHeapTotalSize: number; } export type Headers = Record; export type HttpMethod = 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE' | 'OPTIONS'; export type ResourceType = | 'document' | 'stylesheet' | 'image' | 'media' | 'font' | 'script' | 'texttrack' | 'xhr' | 'fetch' | 'eventsource' | 'websocket' | 'manifest' | 'other'; export type ErrorCode = | 'aborted' | 'accessdenied' | 'addressunreachable' | 'blockedbyclient' | 'blockedbyresponse' | 'connectionaborted' | 'connectionclosed' | 'connectionfailed' | 'connectionrefused' | 'connectionreset' | 'internetdisconnected' | 'namenotresolved' | 'timedout' | 'failed'; export interface Overrides { url?: string | undefined; method?: HttpMethod | undefined; postData?: string | undefined; headers?: Headers | undefined; } /** Represents a page request. */ export interface Request { /** * Aborts request. * To use this, request interception should be enabled with `page.setRequestInterception`. * @throws An exception is immediately thrown if the request interception is not enabled. */ abort(errorCode?: ErrorCode): Promise; /** * Continues request with optional request overrides. * To use this, request interception should be enabled with `page.setRequestInterception`. * @throws An exception is immediately thrown if the request interception is not enabled. */ continue(overrides?: Overrides): Promise; /** * @returns An object if the request failed, null otherwise. */ failure(): { errorText: string } | null; /** * @returns The `Frame` object that initiated the request, or `null` if navigating to error pages */ frame(): Frame | null; /** * An object with HTTP headers associated with the request. * All header names are lower-case. */ headers(): Headers; /** Whether this request is driving frame's navigation. */ isNavigationRequest(): boolean; /** Returns the request's method (GET, POST, etc.) */ method(): HttpMethod; /** Contains the request's post body, if any. */ postData(): string | undefined; /** * A `redirectChain` is a chain of requests initiated to fetch a resource. * * - If there are no redirects and the request was successful, the chain will be empty. * - If a server responds with at least a single redirect, then the chain will contain all the requests that were redirected. * * `redirectChain` is shared between all the requests of the same chain. * * @since 1.2.0 */ redirectChain(): Request[]; /** Contains the request's resource type as it was perceived by the rendering engine. */ resourceType(): ResourceType; /** * Fulfills request with given response. * To use this, request interception should be enabled with `page.setRequestInterception`. * @throws An exception is immediately thrown if the request interception is not enabled. * @param response The response options that will fulfill this request. */ respond(response: RespondOptions): Promise; /** A matching `Response` object, or `null` if the response has not been received yet. */ response(): Response | null; /** Contains the URL of the request. */ url(): string; } /** Options for `Request.respond` method */ export interface RespondOptions { /** * Specifies the response status code. * @default 200 */ status?: number | undefined; /** Specifies the response headers. */ headers?: Headers | undefined; /** Specifies the Content-Type response header. */ contentType?: string | undefined; /** Specifies the response body. */ body?: Buffer | string | undefined; } export interface RemoteInfo { /** the IP address of the remote server */ ip: string; /** the port used to connect to the remote server */ port: number; } export interface SecurityDetails { /** A string with the name of issuer of the certificate. (e.g. "Let's Encrypt Authority X3"). */ issuer(): string; /** String with the security protocol (e.g. TLS 1.2). */ protocol(): string; /** Name of the subject to which the certificate was issued to (e.g. "www.example.com"). */ subjectName(): string; /** Timestamp stating the start of validity of the certificate. */ validFrom(): number; /** Timestamp stating the end of validity of the certificate. */ validTo(): number; } /** Response class represents responses which are received by page. */ export interface Response { /** Promise which resolves to a buffer with response body. */ buffer(): Promise; /** A Frame that initiated this response, or null if navigating to error pages. */ frame(): Frame | null; /** True if the response was served from either the browser's disk cache or memory cache. */ fromCache(): boolean; /** True if the response was served by a service worker. */ fromServiceWorker(): boolean; /** An object with HTTP headers associated with the response. All header names are lower-case. */ headers(): Headers; /** * Promise which resolves to a JSON representation of response body. * @throws This method will throw if the response body is not parsable via `JSON.parse`. */ json(): Promise; /** Contains a boolean stating whether the response was successful (status in the range 200-299) or not. */ ok(): boolean; /** Returns remote connection info */ remoteAddress(): RemoteInfo; /** Returns an object with security details associated with the response. */ securityDetails(): SecurityDetails | null; /** A matching Request object. */ request(): Request; /** Contains the status code of the response (e.g., 200 for a success). */ status(): number; /** Contains the status text of the response (e.g. usually an "OK" for a success). */ statusText(): string; /** Promise which resolves to a text representation of response body. */ text(): Promise; /** Contains the URL of the response. */ url(): string; } export interface WaitForSelectorOptions extends Timeoutable { /** * Wait for element to be present in DOM and to be visible, * i.e. to not have display: none or visibility: hidden CSS properties. * @default false */ visible?: boolean | undefined; /** * Wait for element to not be found in the DOM or to be hidden, * i.e. have display: none or visibility: hidden CSS properties. * @default false */ hidden?: boolean | undefined; } export interface WaitForSelectorOptionsHidden extends WaitForSelectorOptions { hidden: true; } export interface FrameBase extends Evalable, JSEvalable { /** * The method queries frame for the selector. * If there's no such element within the frame, the method will resolve to null. */ $(selector: string): Promise; /** * The method runs document.querySelectorAll within the frame. * If no elements match the selector, the return value resolve to []. */ $$(selector: string): Promise; /** * The method evaluates the XPath expression. * @param expression XPath expression to evaluate. */ $x(expression: string): Promise; /** Adds a `