puppeteer-core

  • Version 10.4.0
  • Published
  • 2.79 MB
  • 12 dependencies
  • Apache-2.0 license

Install

npm i puppeteer-core
yarn add puppeteer-core
pnpm add puppeteer-core

Overview

A high-level API to control headless Chrome over the DevTools Protocol

Index

Variables

Functions

Classes

Interfaces

Enums

Type Aliases

Namespaces

Variables

variable devices

let devices: DevicesMap;

variable errors

let errors: PuppeteerErrors;
  • Modifiers

    • @public

variable EVALUATION_SCRIPT_URL

const EVALUATION_SCRIPT_URL: string;
  • Modifiers

    • @public

variable networkConditions

let networkConditions: PredefinedNetworkConditions;
  • Modifiers

    • @public

variable puppeteerErrors

const puppeteerErrors: PuppeteerErrors;
  • Modifiers

    • @public

Functions

function clearCustomQueryHandlers

clearCustomQueryHandlers: () => void;

function connect

connect: (options: ConnectOptions) => Promise<Browser>;

function customQueryHandlerNames

customQueryHandlerNames: () => string[];

function launch

launch: (
options?: LaunchOptions &
BrowserLaunchArgumentOptions &
BrowserConnectOptions & {
product?: Product;
extraPrefsFirefox?: Record<string, unknown>;
}
) => Promise<Browser>;

function registerCustomQueryHandler

registerCustomQueryHandler: (
name: string,
queryHandler: CustomQueryHandler
) => void;

function unregisterCustomQueryHandler

unregisterCustomQueryHandler: (name: string) => void;

Classes

class Accessibility

class Accessibility {}
  • The Accessibility class provides methods for inspecting Chromium's accessibility tree. The accessibility tree is used by assistive technology such as screen readers or switches.

    Remarks

    Accessibility is a very platform-specific thing. On different platforms, there are different screen readers that might have wildly different output.

    Blink - Chrome's rendering engine - has a concept of "accessibility tree", which is then translated into different platform-specific APIs. Accessibility namespace gives users access to the Blink Accessibility Tree.

    Most of the accessibility tree gets filtered out when converting from Blink AX Tree to Platform-specific AX-Tree or by assistive technologies themselves. By default, Puppeteer tries to approximate this filtering, exposing only the "interesting" nodes of the tree.

    Modifiers

    • @public

method snapshot

snapshot: (options?: SnapshotOptions) => Promise<SerializedAXNode>;
  • Captures the current state of the accessibility tree. The returned object represents the root accessible node of the page.

    Returns

    An AXNode object representing the snapshot.

    Remarks

    **NOTE** The Chromium accessibility tree contains nodes that go unused on most platforms and by most screen readers. Puppeteer will discard them as well for an easier to process tree, unless interestingOnly is set to false.

    Example 1

    An example of dumping the entire accessibility tree:

    const snapshot = await page.accessibility.snapshot();
    console.log(snapshot);

    Example 2

    An example of logging the focused node's name:

    const snapshot = await page.accessibility.snapshot();
    const node = findFocusedNode(snapshot);
    console.log(node && node.name);
    function findFocusedNode(node) {
    if (node.focused)
    return node;
    for (const child of node.children || []) {
    const foundNode = findFocusedNode(child);
    return foundNode;
    }
    return null;
    }

class Browser

class Browser extends EventEmitter {}
  • A Browser is created when Puppeteer connects to a Chromium instance, either through PuppeteerNode.launch or Puppeteer.connect.

    Remarks

    The Browser class extends from Puppeteer's EventEmitter class and will emit various events which are documented in the BrowserEmittedEvents enum.

    Example 1

    An example of using a Browser to create a Page:

    const puppeteer = require('puppeteer');
    (async () => {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.goto('https://example.com');
    await browser.close();
    })();

    Example 2

    An example of disconnecting from and reconnecting to a Browser:

    const puppeteer = require('puppeteer');
    (async () => {
    const browser = await puppeteer.launch();
    // Store the endpoint to be able to reconnect to Chromium
    const browserWSEndpoint = browser.wsEndpoint();
    // Disconnect puppeteer from Chromium
    browser.disconnect();
    // Use the endpoint to reestablish a connection
    const browser2 = await puppeteer.connect({browserWSEndpoint});
    // Close Chromium
    await browser2.close();
    })();

    Modifiers

    • @public

method browserContexts

browserContexts: () => BrowserContext[];
  • Returns an array of all open browser contexts. In a newly created browser, this will return a single instance of BrowserContext.

method close

close: () => Promise<void>;
  • Closes Chromium and all of its pages (if any were opened). The Browser object itself is considered to be disposed and cannot be used anymore.

method createIncognitoBrowserContext

createIncognitoBrowserContext: (
options?: BrowserContextOptions
) => Promise<BrowserContext>;
  • Creates a new incognito browser context. This won't share cookies/cache with other browser contexts.

    Example 1

    (async () => {
    const browser = await puppeteer.launch();
    // Create a new incognito browser context.
    const context = await browser.createIncognitoBrowserContext();
    // Create a new page in a pristine context.
    const page = await context.newPage();
    // Do stuff
    await page.goto('https://example.com');
    })();

method defaultBrowserContext

defaultBrowserContext: () => BrowserContext;
  • Returns the default browser context. The default browser context cannot be closed.

method disconnect

disconnect: () => void;
  • Disconnects Puppeteer from the browser, but leaves the Chromium process running. After calling disconnect, the Browser object is considered disposed and cannot be used anymore.

method isConnected

isConnected: () => boolean;
  • Indicates that the browser is connected.

method newPage

newPage: () => Promise<Page>;
  • Promise which resolves to a new Page object. The Page is created in a default browser context.

method pages

pages: () => Promise<Page[]>;
  • An array of all open pages inside the Browser.

    Remarks

    In case of multiple browser contexts, returns an array with all the pages in all browser contexts. Non-visible pages, such as "background_page", will not be listed here. You can find them using Target.page.

method process

process: () => ChildProcess | null;
  • The spawned browser process. Returns null if the browser instance was created with Puppeteer.connect.

method target

target: () => Target;
  • The target associated with the browser.

method targets

targets: () => Target[];
  • All active targets inside the Browser. In case of multiple browser contexts, returns an array with all the targets in all browser contexts.

method userAgent

userAgent: () => Promise<string>;
  • The browser's original user agent. Pages can override the browser user agent with Page.setUserAgent.

method version

version: () => Promise<string>;
  • A string representing the browser name and version.

    Remarks

    For headless Chromium, this is similar to HeadlessChrome/61.0.3153.0. For non-headless, this is similar to Chrome/61.0.3153.0.

    The format of browser.version() might change with future releases of Chromium.

method waitForTarget

waitForTarget: (
predicate: (x: Target) => boolean,
options?: WaitForTargetOptions
) => Promise<Target>;
  • Searches for a target in all browser contexts.

    Parameter predicate

    A function to be run for every target.

    Returns

    The first target found that matches the predicate function.

    Example 1

    An example of finding a target for a page opened via window.open:

    await page.evaluate(() => window.open('https://www.example.com/'));
    const newWindowTarget = await browser.waitForTarget(target => target.url() === 'https://www.example.com/');

method wsEndpoint

wsEndpoint: () => string;
  • The browser websocket endpoint which can be used as an argument to Puppeteer.connect.

    Returns

    The Browser websocket url.

    Remarks

    The format is ws://${host}:${port}/devtools/browser/<id>.

    You can find the webSocketDebuggerUrl from http://${host}:${port}/json/version. Learn more about the devtools protocol and the browser endpoint.

class BrowserContext

class BrowserContext extends EventEmitter {}
  • BrowserContexts provide a way to operate multiple independent browser sessions. When a browser is launched, it has a single BrowserContext used by default. The method Browser.newPage creates a page in the default browser context.

    Remarks

    The Browser class extends from Puppeteer's EventEmitter class and will emit various events which are documented in the BrowserContextEmittedEvents enum.

    If a page opens another page, e.g. with a window.open call, the popup will belong to the parent page's browser context.

    Puppeteer allows creation of "incognito" browser contexts with Browser.createIncognitoBrowserContext method. "Incognito" browser contexts don't write any browsing data to disk.

    Example 1

    // Create a new incognito browser context
    const context = await browser.createIncognitoBrowserContext();
    // Create a new page inside context.
    const page = await context.newPage();
    // ... do stuff with page ...
    await page.goto('https://example.com');
    // Dispose context once it's no longer needed.
    await context.close();

    Modifiers

    • @public

method browser

browser: () => Browser;
  • The browser this browser context belongs to.

method clearPermissionOverrides

clearPermissionOverrides: () => Promise<void>;
  • Clears all permission overrides for the browser context.

    Example 1

    const context = browser.defaultBrowserContext();
    context.overridePermissions('https://example.com', ['clipboard-read']);
    // do stuff ..
    context.clearPermissionOverrides();

method close

close: () => Promise<void>;
  • Closes the browser context. All the targets that belong to the browser context will be closed.

    Remarks

    Only incognito browser contexts can be closed.

method isIncognito

isIncognito: () => boolean;
  • Returns whether BrowserContext is incognito. The default browser context is the only non-incognito browser context.

    Remarks

    The default browser context cannot be closed.

method newPage

newPage: () => Promise<Page>;
  • Creates a new page in the browser context.

method overridePermissions

overridePermissions: (
origin: string,
permissions: Permission[]
) => Promise<void>;
  • Parameter origin

    The origin to grant permissions to, e.g. "https://example.com".

    Parameter permissions

    An array of permissions to grant. All permissions that are not listed here will be automatically denied.

    Example 1

    const context = browser.defaultBrowserContext();
    await context.overridePermissions('https://html5demos.com', ['geolocation']);

method pages

pages: () => Promise<Page[]>;
  • An array of all pages inside the browser context.

    Returns

    Promise which resolves to an array of all open pages. Non visible pages, such as "background_page", will not be listed here. You can find them using the target page.

method targets

targets: () => Target[];
  • An array of all active targets inside the browser context.

method waitForTarget

waitForTarget: (
predicate: (x: Target) => boolean,
options?: { timeout?: number }
) => Promise<Target>;
  • This searches for a target in this specific browser context.

    Parameter predicate

    A function to be run for every target

    Parameter options

    An object of options. Accepts a timout, which is the maximum wait time in milliseconds. Pass 0 to disable the timeout. Defaults to 30 seconds.

    Returns

    Promise which resolves to the first target found that matches the predicate function.

    Example 1

    An example of finding a target for a page opened via window.open:

    await page.evaluate(() => window.open('https://www.example.com/'));
    const newWindowTarget = await browserContext.waitForTarget(target => target.url() === 'https://www.example.com/');

class BrowserFetcher

class BrowserFetcher {}
  • BrowserFetcher can download and manage different versions of Chromium and Firefox.

    Remarks

    BrowserFetcher operates on revision strings that specify a precise version of Chromium, e.g. "533271". Revision strings can be obtained from omahaproxy.appspot.com. In the Firefox case, BrowserFetcher downloads Firefox Nightly and operates on version numbers such as "75".

    Example 1

    An example of using BrowserFetcher to download a specific version of Chromium and running Puppeteer against it:

    const browserFetcher = puppeteer.createBrowserFetcher();
    const revisionInfo = await browserFetcher.download('533271');
    const browser = await puppeteer.launch({executablePath: revisionInfo.executablePath})

    **NOTE** BrowserFetcher is not designed to work concurrently with other instances of BrowserFetcher that share the same downloads directory.

    Modifiers

    • @public

method canDownload

canDownload: (revision: string) => Promise<boolean>;
  • Initiates a HEAD request to check if the revision is available.

    Parameter revision

    The revision to check availability for.

    Returns

    A promise that resolves to true if the revision could be downloaded from the host.

    Remarks

    This method is affected by the current product.

method download

download: (
revision: string,
progressCallback?: (x: number, y: number) => void
) => Promise<BrowserFetcherRevisionInfo>;
  • Initiates a GET request to download the revision from the host.

    Parameter revision

    The revision to download.

    Parameter progressCallback

    A function that will be called with two arguments: How many bytes have been downloaded and the total number of bytes of the download.

    Returns

    A promise with revision information when the revision is downloaded and extracted.

    Remarks

    This method is affected by the current product.

method host

host: () => string;
  • Returns

    The download host being used.

method localRevisions

localRevisions: () => Promise<string[]>;
  • Returns

    A promise with a list of all revision strings (for the current product) available locally on disk.

    Remarks

    This method is affected by the current product.

method platform

platform: () => Platform;
  • Returns

    Returns the current Platform, which is one of mac, linux, win32 or win64.

method product

product: () => Product;
  • Returns

    Returns the current Product, which is one of chrome or firefox.

method remove

remove: (revision: string) => Promise<void>;
  • Parameter revision

    A revision to remove for the current product.

    Returns

    A promise that resolves when the revision has been removes or throws if the revision has not been downloaded.

    Remarks

    This method is affected by the current product.

method revisionInfo

revisionInfo: (revision: string) => BrowserFetcherRevisionInfo;
  • Parameter revision

    The revision to get info for.

    Returns

    The revision info for the given revision.

class CDPSession

class CDPSession extends EventEmitter {}
  • The CDPSession instances are used to talk raw Chrome Devtools Protocol.

    Remarks

    Protocol methods can be called with CDPSession.send method and protocol events can be subscribed to with CDPSession.on method.

    Useful links: DevTools Protocol Viewer and Getting Started with DevTools Protocol.

    Example 1

    const client = await page.target().createCDPSession();
    await client.send('Animation.enable');
    client.on('Animation.animationCreated', () => console.log('Animation created!'));
    const response = await client.send('Animation.getPlaybackRate');
    console.log('playback rate is ' + response.playbackRate);
    await client.send('Animation.setPlaybackRate', {
    playbackRate: response.playbackRate / 2
    });

    Modifiers

    • @public

method connection

connection: () => Connection;

    method detach

    detach: () => Promise<void>;
    • Detaches the cdpSession from the target. Once detached, the cdpSession object won't emit any events and can't be used to send messages.

    method send

    send: <T extends string | number | symbol>(
    method: T,
    ...paramArgs: any
    ) => Promise<ProtocolMapping.Commands[T]['returnType']>;

      class Connection

      class Connection extends EventEmitter {}
      • Modifiers

        • @public

      constructor

      constructor(url: string, transport: ConnectionTransport, delay?: number);

        method createSession

        createSession: (targetInfo: any) => Promise<CDPSession>;
        • Parameter targetInfo

          The target info

          Returns

          The CDP session that is created

        method dispose

        dispose: () => void;

          method fromSession

          static fromSession: (session: CDPSession) => Connection;

            method send

            send: <T extends string | number | symbol>(
            method: T,
            ...paramArgs: any
            ) => Promise<ProtocolMapping.Commands[T]['returnType']>;

              method session

              session: (sessionId: string) => CDPSession | null;
              • Parameter sessionId

                The session id

                Returns

                The current CDP session if it exists

              method url

              url: () => string;

                class ConsoleMessage

                class ConsoleMessage {}
                • ConsoleMessage objects are dispatched by page via the 'console' event.

                  Modifiers

                  • @public

                constructor

                constructor(
                type: ConsoleMessageType,
                text: string,
                args: JSHandle<unknown>[],
                stackTraceLocations: ConsoleMessageLocation[]
                );
                • Modifiers

                  • @public

                method args

                args: () => JSHandle[];
                • Returns

                  An array of arguments passed to the console.

                method location

                location: () => ConsoleMessageLocation;
                • Returns

                  The location of the console message.

                method stackTrace

                stackTrace: () => ConsoleMessageLocation[];
                • Returns

                  The array of locations on the stack of the console message.

                method text

                text: () => string;
                • Returns

                  The text of the console message.

                method type

                type: () => ConsoleMessageType;
                • Returns

                  The type of the console message.

                class Coverage

                class Coverage {}
                • The Coverage class provides methods to gathers information about parts of JavaScript and CSS that were used by the page.

                  Remarks

                  To output coverage in a form consumable by Istanbul, see puppeteer-to-istanbul.

                  Example 1

                  An example of using JavaScript and CSS coverage to get percentage of initially executed code:

                  // Enable both JavaScript and CSS coverage
                  await Promise.all([
                  page.coverage.startJSCoverage(),
                  page.coverage.startCSSCoverage()
                  ]);
                  // Navigate to page
                  await page.goto('https://example.com');
                  // Disable both JavaScript and CSS coverage
                  const [jsCoverage, cssCoverage] = await Promise.all([
                  page.coverage.stopJSCoverage(),
                  page.coverage.stopCSSCoverage(),
                  ]);
                  let totalBytes = 0;
                  let usedBytes = 0;
                  const coverage = [...jsCoverage, ...cssCoverage];
                  for (const entry of coverage) {
                  totalBytes += entry.text.length;
                  for (const range of entry.ranges)
                  usedBytes += range.end - range.start - 1;
                  }
                  console.log(`Bytes used: ${usedBytes / totalBytes * 100}%`);

                  Modifiers

                  • @public

                constructor

                constructor(client: CDPSession);

                  method startCSSCoverage

                  startCSSCoverage: (options?: CSSCoverageOptions) => Promise<void>;
                  • Parameter options

                    Set of configurable options for coverage, defaults to resetOnNavigation : true

                    Returns

                    Promise that resolves when coverage is started.

                  method startJSCoverage

                  startJSCoverage: (options?: JSCoverageOptions) => Promise<void>;
                  • Parameter options

                    Set of configurable options for coverage defaults to resetOnNavigation : true, reportAnonymousScripts : false

                    Returns

                    Promise that resolves when coverage is started.

                    Remarks

                    Anonymous scripts are ones that don't have an associated url. These are scripts that are dynamically created on the page using eval or new Function. If reportAnonymousScripts is set to true, anonymous scripts will have __puppeteer_evaluation_script__ as their URL.

                  method stopCSSCoverage

                  stopCSSCoverage: () => Promise<CoverageEntry[]>;
                  • Returns

                    Promise that resolves to the array of coverage reports for all stylesheets.

                    Remarks

                    CSS Coverage doesn't include dynamically injected style tags without sourceURLs.

                  method stopJSCoverage

                  stopJSCoverage: () => Promise<JSCoverageEntry[]>;
                  • Returns

                    Promise that resolves to the array of coverage reports for all scripts.

                    Remarks

                    JavaScript Coverage doesn't include anonymous scripts by default. However, scripts with sourceURLs are reported.

                  class CSSCoverage

                  class CSSCoverage {}
                  • Modifiers

                    • @public

                  constructor

                  constructor(client: CDPSession);

                    method start

                    start: (options?: { resetOnNavigation?: boolean }) => Promise<void>;

                      method stop

                      stop: () => Promise<CoverageEntry[]>;

                        class CustomError

                        class CustomError extends Error {}
                        • Modifiers

                          • @public

                        constructor

                        constructor(message: string);

                          class Dialog

                          class Dialog {}
                          • Dialog instances are dispatched by the Page via the dialog event.

                            Remarks

                            Example 1

                            const puppeteer = require('puppeteer');
                            (async () => {
                            const browser = await puppeteer.launch();
                            const page = await browser.newPage();
                            page.on('dialog', async dialog => {
                            console.log(dialog.message());
                            await dialog.dismiss();
                            await browser.close();
                            });
                            page.evaluate(() => alert('1'));
                            })();

                            Modifiers

                            • @public

                          method accept

                          accept: (promptText?: string) => Promise<void>;
                          • Parameter promptText

                            optional text that will be entered in the dialog prompt. Has no effect if the dialog's type is not prompt.

                            Returns

                            A promise that resolves when the dialog has been accepted.

                          method defaultValue

                          defaultValue: () => string;
                          • Returns

                            The default value of the prompt, or an empty string if the dialog is not a prompt.

                          method dismiss

                          dismiss: () => Promise<void>;
                          • Returns

                            A promise which will resolve once the dialog has been dismissed

                          method message

                          message: () => string;
                          • Returns

                            The message displayed in the dialog.

                          method type

                          type: () => any;
                          • Returns

                            The type of the dialog.

                          class ElementHandle

                          class ElementHandle<
                          ElementType extends Element = Element
                          > extends JSHandle<ElementType> {}
                          • ElementHandle represents an in-page DOM element.

                            Remarks

                            ElementHandles can be created with the Page.$ method.

                            const puppeteer = require('puppeteer');
                            (async () => {
                            const browser = await puppeteer.launch();
                            const page = await browser.newPage();
                            await page.goto('https://example.com');
                            const hrefElement = await page.$('a');
                            await hrefElement.click();
                            // ...
                            })();

                            ElementHandle prevents the DOM element from being garbage-collected unless the handle is disposed. ElementHandles are auto-disposed when their origin frame gets navigated.

                            ElementHandle instances can be used as arguments in Page.$eval and Page.evaluate methods.

                            If you're using TypeScript, ElementHandle takes a generic argument that denotes the type of element the handle is holding within. For example, if you have a handle to a <select> element, you can type it as ElementHandle<HTMLSelectElement> and you get some nicer type checks.

                            Modifiers

                            • @public

                          method $

                          $: <T extends Element = Element>(
                          selector: string
                          ) => Promise<ElementHandle<T> | null>;
                          • Runs element.querySelector within the page. If no element matches the selector, the return value resolves to null.

                          method $$

                          $$: <T extends Element = Element>(
                          selector: string
                          ) => Promise<Array<ElementHandle<T>>>;
                          • Runs element.querySelectorAll within the page. If no elements match the selector, the return value resolves to [].

                          method $$eval

                          $$eval: <ReturnType>(
                          selector: string,
                          pageFunction: (
                          elements: Element[],
                          ...args: unknown[]
                          ) => ReturnType | Promise<ReturnType>,
                          ...args: SerializableOrJSHandle[]
                          ) => Promise<WrapElementHandle<ReturnType>>;
                          • This method runs document.querySelectorAll within the element 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 frame.$$eval would wait for the promise to resolve and return its value.

                            Example 1

                            <div class="feed">
                            <div class="tweet">Hello!</div>
                            <div class="tweet">Hi!</div>
                            </div>

                            Example 2

                            const feedHandle = await page.$('.feed');
                            expect(await feedHandle.$$eval('.tweet', nodes => nodes.map(n => n.innerText)))
                            .toEqual(['Hello!', 'Hi!']);

                          method $eval

                          $eval: <ReturnType>(
                          selector: string,
                          pageFunction: (
                          element: Element,
                          ...args: unknown[]
                          ) => ReturnType | Promise<ReturnType>,
                          ...args: SerializableOrJSHandle[]
                          ) => Promise<WrapElementHandle<ReturnType>>;
                          • This method runs document.querySelector within the element 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 frame.$eval would wait for the promise to resolve and return its value.

                            Example 1

                            const tweetHandle = await page.$('.tweet');
                            expect(await tweetHandle.$eval('.like', node => node.innerText)).toBe('100');
                            expect(await tweetHandle.$eval('.retweets', node => node.innerText)).toBe('10');

                          method $x

                          $x: (expression: string) => Promise<ElementHandle[]>;
                          • The method evaluates the XPath expression relative to the elementHandle. If there are no such elements, the method will resolve to an empty array.

                            Parameter expression

                            Expression to evaluate

                          method asElement

                          asElement: () => ElementHandle<ElementType> | null;

                            method boundingBox

                            boundingBox: () => Promise<BoundingBox | null>;
                            • This method returns the bounding box of the element (relative to the main frame), or null if the element is not visible.

                            method boxModel

                            boxModel: () => Promise<BoxModel | null>;
                            • This method returns boxes of the element, or null if the element is not visible.

                              Remarks

                              Boxes are represented as an array of points; Each Point is an object {x, y}. Box points are sorted clock-wise.

                            method click

                            click: (options?: ClickOptions) => Promise<void>;
                            • 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.

                            method clickablePoint

                            clickablePoint: (offset?: Offset) => Promise<Point>;
                            • Returns the middle point within an element unless a specific offset is provided.

                            method contentFrame

                            contentFrame: () => Promise<Frame | null>;
                            • Resolves to the content frame for element handles referencing iframe nodes, or null otherwise

                            method drag

                            drag: (target: Point) => Promise<Protocol.Input.DragData>;
                            • This method creates and captures a dragevent from the element.

                            method dragAndDrop

                            dragAndDrop: (
                            target: ElementHandle,
                            options?: { delay: number }
                            ) => Promise<void>;
                            • This method triggers a dragenter, dragover, and drop on the element.

                            method dragEnter

                            dragEnter: (data?: any) => Promise<void>;
                            • This method creates a dragenter event on the element.

                            method dragOver

                            dragOver: (data?: any) => Promise<void>;
                            • This method creates a dragover event on the element.

                            method drop

                            drop: (data?: any) => Promise<void>;
                            • This method triggers a drop on the element.

                            method focus

                            focus: () => Promise<void>;
                            • Calls focus on the element.

                            method hover

                            hover: () => Promise<void>;
                            • 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.

                            method isIntersectingViewport

                            isIntersectingViewport: (options?: { threshold?: number }) => Promise<boolean>;
                            • Resolves to true if the element is visible in the current viewport.

                            method press

                            press: (key: KeyInput, options?: PressOptions) => Promise<void>;
                            • Focuses the element, and then uses Keyboard.down and Keyboard.up.

                              Parameter key

                              Name of key to press, such as ArrowLeft. See KeyInput for a list of all key names.

                              Remarks

                              If key is a single character and no modifier keys besides Shift are being held down, a keypress/input event will also be generated. The text option can be specified to force an input event to be generated.

                              **NOTE** Modifier keys DO affect elementHandle.press. Holding down Shift will type the text in upper case.

                            method screenshot

                            screenshot: (options?: {}) => Promise<string | Buffer | void>;
                            • 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.

                            method select

                            select: (...values: string[]) => Promise<string[]>;
                            • Triggers a change and input event once all the provided options have been selected. If there's no <select> element matching selector, the method throws an error.

                              Parameter 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.

                              Example 1

                              handle.select('blue'); // single selection
                              handle.select('red', 'green', 'blue'); // multiple selections

                            method tap

                            tap: () => Promise<void>;
                            • 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.

                            method type

                            type: (text: string, options?: { delay: number }) => Promise<void>;
                            • Focuses the element, and then sends a keydown, keypress/input, and keyup event for each character in the text.

                              To press a special key, like Control or ArrowDown, use ElementHandle.press.

                              Example 1

                              await elementHandle.type('Hello'); // Types instantly
                              await elementHandle.type('World', {delay: 100}); // Types slower, like a user

                              Example 2

                              An example of typing into a text field and then submitting the form:

                              const elementHandle = await page.$('input');
                              await elementHandle.type('some text');
                              await elementHandle.press('Enter');

                            method uploadFile

                            uploadFile: (...filePaths: string[]) => Promise<void>;
                            • This method expects elementHandle to point to an input element.

                              Parameter filePaths

                              Sets the value of the file input to these paths. If some of the filePaths are relative paths, then they are resolved relative to the current working directory

                            class EventEmitter

                            class EventEmitter implements CommonEventEmitter {}
                            • The EventEmitter class that many Puppeteer classes extend.

                              Remarks

                              This allows you to listen to events that Puppeteer classes fire and act accordingly. Therefore you'll mostly use on and off to bind and unbind to event listeners.

                              Modifiers

                              • @public

                            method addListener

                            addListener: (event: EventType, handler: Handler) => EventEmitter;

                            method emit

                            emit: (event: EventType, eventData?: unknown) => boolean;
                            • Emit an event and call any associated listeners.

                              Parameter event

                              the event you'd like to emit

                              Parameter eventData

                              any data you'd like to emit with the event

                              Returns

                              true if there are any listeners, false if there are not.

                            method listenerCount

                            listenerCount: (event: EventType) => number;
                            • Gets the number of listeners for a given event.

                              Parameter event

                              the event to get the listener count for

                              Returns

                              the number of listeners bound to the given event

                            method off

                            off: (event: EventType, handler: Handler) => EventEmitter;
                            • Remove an event listener from firing.

                              Parameter event

                              the event type you'd like to stop listening to.

                              Parameter handler

                              the function that should be removed.

                              Returns

                              this to enable you to chain method calls.

                            method on

                            on: (event: EventType, handler: Handler) => EventEmitter;
                            • Bind an event listener to fire when an event occurs.

                              Parameter event

                              the event type you'd like to listen to. Can be a string or symbol.

                              Parameter handler

                              the function to be called when the event occurs.

                              Returns

                              this to enable you to chain method calls.

                            method once

                            once: (event: EventType, handler: Handler) => EventEmitter;
                            • Like on but the listener will only be fired once and then it will be removed.

                              Parameter event

                              the event you'd like to listen to

                              Parameter handler

                              the handler function to run when the event occurs

                              Returns

                              this to enable you to chain method calls.

                            method removeAllListeners

                            removeAllListeners: (event?: EventType) => EventEmitter;
                            • Removes all listeners. If given an event argument, it will remove only listeners for that event.

                              Parameter event

                              the event to remove listeners for.

                              Returns

                              this to enable you to chain method calls.

                            method removeListener

                            removeListener: (event: EventType, handler: Handler) => EventEmitter;

                            class ExecutionContext

                            class ExecutionContext {}
                            • This class represents a context for JavaScript execution. A [Page] might have many execution contexts: - each frame has "default" execution context that is always created after frame is attached to DOM. This context is returned by the Frame.executionContext method. - Extension's content scripts create additional execution contexts.

                              Besides pages, execution contexts can be found in workers.

                              Modifiers

                              • @public

                            method evaluate

                            evaluate: <ReturnType extends unknown>(
                            pageFunction: Function | string,
                            ...args: unknown[]
                            ) => Promise<ReturnType>;
                            • Parameter pageFunction

                              a function to be evaluated in the executionContext

                              Parameter args

                              argument to pass to the page function

                              Returns

                              A promise that resolves to the return value of the given function.

                              Remarks

                              If the function passed to the executionContext.evaluate returns a Promise, then executionContext.evaluate would wait for the promise to resolve and return its value. If the function passed to the executionContext.evaluate returns a non-serializable value, then executionContext.evaluate resolves to undefined. DevTools Protocol also supports transferring some additional values that are not serializable by JSON: -0, NaN, Infinity, -Infinity, and bigint literals.

                              Example 1

                              const executionContext = await page.mainFrame().executionContext();
                              const result = await executionContext.evaluate(() => Promise.resolve(8 * 7))* ;
                              console.log(result); // prints "56"

                              Example 2

                              A string can also be passed in instead of a function.

                              console.log(await executionContext.evaluate('1 + 2')); // prints "3"

                              Example 3

                              JSHandle instances can be passed as arguments to the executionContext.* evaluate:

                              const oneHandle = await executionContext.evaluateHandle(() => 1);
                              const twoHandle = await executionContext.evaluateHandle(() => 2);
                              const result = await executionContext.evaluate(
                              (a, b) => a + b, oneHandle, * twoHandle
                              );
                              await oneHandle.dispose();
                              await twoHandle.dispose();
                              console.log(result); // prints '3'.

                            method evaluateHandle

                            evaluateHandle: <
                            HandleType extends
                            | JSHandle<unknown>
                            | ElementHandle<Element> = JSHandle<unknown>
                            >(
                            pageFunction: EvaluateHandleFn,
                            ...args: SerializableOrJSHandle[]
                            ) => Promise<HandleType>;
                            • Parameter pageFunction

                              a function to be evaluated in the executionContext

                              Parameter args

                              argument to pass to the page function

                              Returns

                              A promise that resolves to the return value of the given function as an in-page object (a JSHandle).

                              Remarks

                              The only difference between executionContext.evaluate and executionContext.evaluateHandle is that executionContext.evaluateHandle returns an in-page object (a JSHandle). If the function passed to the executionContext.evaluateHandle returns a Promise, then executionContext.evaluateHandle would wait for the promise to resolve and return its value.

                              Example 1

                              const context = await page.mainFrame().executionContext();
                              const aHandle = await context.evaluateHandle(() => Promise.resolve(self));
                              aHandle; // Handle for the global object.

                              Example 2

                              A string can also be passed in instead of a function.

                              // Handle for the '3' * object.
                              const aHandle = await context.evaluateHandle('1 + 2');

                              Example 3

                              JSHandle instances can be passed as arguments to the executionContext.* evaluateHandle:

                              const aHandle = await context.evaluateHandle(() => document.body);
                              const resultHandle = await context.evaluateHandle(body => body.innerHTML, * aHandle);
                              console.log(await resultHandle.jsonValue()); // prints body's innerHTML
                              await aHandle.dispose();
                              await resultHandle.dispose();

                            method frame

                            frame: () => Frame | null;
                            • Returns

                              The frame associated with this execution context.

                              Remarks

                              Not every execution context is associated with a frame. For example, workers and extensions have execution contexts that are not associated with frames.

                            method queryObjects

                            queryObjects: (prototypeHandle: JSHandle) => Promise<JSHandle>;
                            • This method iterates the JavaScript heap and finds all the objects with the given prototype.

                              Parameter prototypeHandle

                              a handle to the object prototype

                              Returns

                              A handle to an array of objects with the given prototype.

                              Remarks

                              Example 1

                              // Create a Map object
                              await page.evaluate(() => window.map = new Map());
                              // Get a handle to the Map object prototype
                              const mapPrototype = await page.evaluateHandle(() => Map.prototype);
                              // Query all map instances into an array
                              const mapInstances = await page.queryObjects(mapPrototype);
                              // Count amount of map objects in heap
                              const count = await page.evaluate(maps => maps.length, mapInstances);
                              await mapInstances.dispose();
                              await mapPrototype.dispose();

                            class FileChooser

                            class FileChooser {}
                            • File choosers let you react to the page requesting for a file.

                              Remarks

                              FileChooser objects are returned via the page.waitForFileChooser method.

                              Example 1

                              An example of using FileChooser:

                              const [fileChooser] = await Promise.all([
                              page.waitForFileChooser(),
                              page.click('#upload-file-button'), // some button that triggers file selection
                              ]);
                              await fileChooser.accept(['/tmp/myfile.pdf']);

                              **NOTE** In browsers, only one file chooser can be opened at a time. All file choosers must be accepted or canceled. Not doing so will prevent subsequent file choosers from appearing.

                              Modifiers

                              • @public

                            method accept

                            accept: (filePaths: string[]) => Promise<void>;
                            • Accept the file chooser request with given paths.

                              Parameter filePaths

                              If some of the filePaths are relative paths, then they are resolved relative to the current working directory.

                            method cancel

                            cancel: () => void;
                            • Closes the file chooser without selecting any files.

                            method isMultiple

                            isMultiple: () => boolean;
                            • Whether file chooser allow for multiple file selection.

                            class Frame

                            class Frame {}
                            • At every point of time, page exposes its current frame tree via the page.mainFrame and frame.childFrames methods.

                              Remarks

                              Frame object lifecycles are controlled by three events that are all dispatched on the page object:

                              - PageEmittedEvents.FrameAttached

                              - PageEmittedEvents.FrameNavigated

                              - PageEmittedEvents.FrameDetached

                              Example 1

                              An example of dumping frame tree:

                              const puppeteer = require('puppeteer');
                              (async () => {
                              const browser = await puppeteer.launch();
                              const page = await browser.newPage();
                              await page.goto('https://www.google.com/chrome/browser/canary.html');
                              dumpFrameTree(page.mainFrame(), '');
                              await browser.close();
                              function dumpFrameTree(frame, indent) {
                              console.log(indent + frame.url());
                              for (const child of frame.childFrames()) {
                              dumpFrameTree(child, indent + ' ');
                              }
                              }
                              })();

                              Example 2

                              An example of getting text from an iframe element:

                              const frame = page.frames().find(frame => frame.name() === 'myframe');
                              const text = await frame.$eval('.selector', element => element.textContent);
                              console.log(text);

                              Modifiers

                              • @public

                            method $

                            $: <T extends Element = Element>(
                            selector: string
                            ) => Promise<ElementHandle<T> | null>;
                            • This method queries the frame for the given selector.

                              Parameter selector

                              a selector to query for.

                              Returns

                              A promise which resolves to an ElementHandle pointing at the element, or null if it was not found.

                            method $$

                            $$: <T extends Element = Element>(
                            selector: string
                            ) => Promise<Array<ElementHandle<T>>>;
                            • This runs document.querySelectorAll in the frame and returns the result.

                              Parameter selector

                              a selector to search for

                              Returns

                              An array of element handles pointing to the found frame elements.

                            method $$eval

                            $$eval: <ReturnType>(
                            selector: string,
                            pageFunction: (
                            elements: Element[],
                            ...args: unknown[]
                            ) => ReturnType | Promise<ReturnType>,
                            ...args: SerializableOrJSHandle[]
                            ) => Promise<WrapElementHandle<ReturnType>>;
                            • Parameter selector

                              the selector to query for

                              Parameter pageFunction

                              the function to be evaluated in the frame's context

                              Parameter args

                              additional arguments to pass to pageFuncton

                              Remarks

                              This method runs Array.from(document.querySelectorAll(selector)) within the frame and passes it as the first argument to pageFunction.

                              If pageFunction returns a Promise, then frame.$$eval would wait for the promise to resolve and return its value.

                              Example 1

                              const divsCounts = await frame.$$eval('div', divs => divs.length);

                            method $eval

                            $eval: <ReturnType>(
                            selector: string,
                            pageFunction: (
                            element: Element,
                            ...args: unknown[]
                            ) => ReturnType | Promise<ReturnType>,
                            ...args: SerializableOrJSHandle[]
                            ) => Promise<WrapElementHandle<ReturnType>>;
                            • Parameter selector

                              the selector to query for

                              Parameter pageFunction

                              the function to be evaluated in the frame's context

                              Parameter args

                              additional arguments to pass to pageFuncton

                              Remarks

                              This method runs document.querySelector within the frame and passes it as the first argument to pageFunction.

                              If pageFunction returns a Promise, then frame.$eval would wait for the promise to resolve and return its value.

                              Example 1

                              const searchValue = await frame.$eval('#search', el => el.value);

                            method $x

                            $x: (expression: string) => Promise<ElementHandle[]>;
                            • This method evaluates the given XPath expression and returns the results.

                              Parameter expression

                              the XPath expression to evaluate.

                            method addScriptTag

                            addScriptTag: (options: FrameAddScriptTagOptions) => Promise<ElementHandle>;
                            • Adds a <script> tag into the page with the desired url or content.

                              Parameter options

                              configure the script to add to the page.

                              Returns

                              a promise that resolves to the added tag when the script's onload event fires or when the script content was injected into the frame.

                            method addStyleTag

                            addStyleTag: (options: FrameAddStyleTagOptions) => Promise<ElementHandle>;
                            • Adds a <link rel="stylesheet"> tag into the page with the desired url or a <style type="text/css"> tag with the content.

                              Parameter options

                              configure the CSS to add to the page.

                              Returns

                              a promise that resolves to the added tag when the stylesheets's onload event fires or when the CSS content was injected into the frame.

                            method childFrames

                            childFrames: () => Frame[];
                            • Returns

                              an array of child frames.

                            method click

                            click: (
                            selector: string,
                            options?: { delay?: number; button?: MouseButton; clickCount?: number }
                            ) => Promise<void>;
                            • This method clicks the first element found that matches selector.

                              Parameter selector

                              the selector to search for to click. If there are multiple elements, the first will be clicked.

                              Remarks

                              This method scrolls the element into view if needed, and then uses Page.mouse to click in the center of the element. If there's no element matching selector, the method throws an error.

                              Bear in mind that if click() triggers a navigation event and there's a separate page.waitForNavigation() promise to be resolved, you may end up with a race condition that yields unexpected results. The correct pattern for click and wait for navigation is the following:

                              const [response] = await Promise.all([
                              page.waitForNavigation(waitOptions),
                              frame.click(selector, clickOptions),
                              ]);

                            method content

                            content: () => Promise<string>;
                            • Returns

                              the full HTML contents of the frame, including the doctype.

                            method evaluate

                            evaluate: <T extends EvaluateFn<any>>(
                            pageFunction: T,
                            ...args: SerializableOrJSHandle[]
                            ) => Promise<UnwrapPromiseLike<EvaluateFnReturnType<T>>>;
                            • Parameter pageFunction

                              a function that is run within the frame

                              Parameter args

                              arguments to be passed to the pageFunction

                              Remarks

                              This method behaves identically to Page.evaluate except it's run within the context of the frame, rather than the entire page.

                            method evaluateHandle

                            evaluateHandle: <HandlerType extends JSHandle<unknown> = JSHandle<unknown>>(
                            pageFunction: EvaluateHandleFn,
                            ...args: SerializableOrJSHandle[]
                            ) => Promise<HandlerType>;
                            • Parameter pageFunction

                              a function that is run within the frame

                              Parameter args

                              arguments to be passed to the pageFunction

                              Remarks

                              The only difference between Frame.evaluate and frame.evaluateHandle is that evaluateHandle will return the value wrapped in an in-page object.

                              This method behaves identically to Page.evaluateHandle except it's run within the context of the frame, rather than the entire page.

                            method executionContext

                            executionContext: () => Promise<ExecutionContext>;
                            • Returns

                              a promise that resolves to the frame's default execution context.

                            method focus

                            focus: (selector: string) => Promise<void>;
                            • This method fetches an element with selector and focuses it.

                              Parameter selector

                              the selector for the element to focus. If there are multiple elements, the first will be focused.

                              Remarks

                              If there's no element matching selector, the method throws an error.

                            method goto

                            goto: (
                            url: string,
                            options?: {
                            referer?: string;
                            timeout?: number;
                            waitUntil?: PuppeteerLifeCycleEvent | PuppeteerLifeCycleEvent[];
                            }
                            ) => Promise<HTTPResponse | null>;
                            • Parameter url

                              the URL to navigate the frame to. This should include the scheme, e.g. https://.

                              Parameter options

                              navigation options. waitUntil is useful to define when the navigation should be considered successful - see the docs for PuppeteerLifeCycleEvent for more details.

                              Returns

                              A promise which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect.

                              Remarks

                              frame.goto will throw an error if: - there's an SSL error (e.g. in case of self-signed certificates).

                              - target URL is invalid.

                              - the timeout is exceeded during navigation.

                              - the remote server does not respond or is unreachable.

                              - the main resource failed to load.

                              frame.goto will not throw an error when any valid HTTP status code is returned by the remote server, including 404 "Not Found" and 500 "Internal Server Error". The status code for such responses can be retrieved by calling HTTPResponse.status.

                              NOTE: frame.goto either throws an error or returns a main resource response. The only exceptions are navigation to about:blank or navigation to the same URL with a different hash, which would succeed and return null.

                              NOTE: Headless mode doesn't support navigation to a PDF document. See the upstream issue.

                            method hover

                            hover: (selector: string) => Promise<void>;
                            • This method fetches an element with selector, scrolls it into view if needed, and then uses Page.mouse to hover over the center of the element.

                              Parameter selector

                              the selector for the element to hover. If there are multiple elements, the first will be hovered.

                              Remarks

                              If there's no element matching selector, the method throws an

                            method isDetached

                            isDetached: () => boolean;
                            • Returns

                              true if the frame has been detached, or false otherwise.

                            method name

                            name: () => string;
                            • Returns

                              the frame's name attribute as specified in the tag.

                              Remarks

                              If the name is empty, it returns the id attribute instead.

                              Note: This value is calculated once when the frame is created, and will not update if the attribute is changed later.

                            method parentFrame

                            parentFrame: () => Frame | null;
                            • Returns

                              the parent Frame, if any. Detached and main frames return null.

                            method select

                            select: (selector: string, ...values: string[]) => Promise<string[]>;
                            • Triggers a change and input event once all the provided options have been selected.

                              Parameter selector

                              a selector to query the frame for

                              Parameter values

                              an array of values to select. If the <select> has the multiple attribute, all values are considered, otherwise only the first one is taken into account.

                              Returns

                              the list of values that were successfully selected.

                              Remarks

                              If there's no <select> element matching selector, the method throws an error.

                              Example 1

                              frame.select('select#colors', 'blue'); // single selection
                              frame.select('select#colors', 'red', 'green', 'blue'); // multiple selections

                            method setContent

                            setContent: (
                            html: string,
                            options?: {
                            timeout?: number;
                            waitUntil?: PuppeteerLifeCycleEvent | PuppeteerLifeCycleEvent[];
                            }
                            ) => Promise<void>;
                            • Set the content of the frame.

                              Parameter html

                              HTML markup to assign to the page.

                              Parameter options

                              options to configure how long before timing out and at what point to consider the content setting successful.

                            method tap

                            tap: (selector: string) => Promise<void>;
                            • This method fetches an element with selector, scrolls it into view if needed, and then uses Page.touchscreen to tap in the center of the element.

                              Parameter selector

                              the selector to tap.

                              Returns

                              a promise that resolves when the element has been tapped.

                              Remarks

                              If there's no element matching selector, the method throws an error.

                            method title

                            title: () => Promise<string>;
                            • Returns

                              the frame's title.

                            method type

                            type: (
                            selector: string,
                            text: string,
                            options?: { delay: number }
                            ) => Promise<void>;
                            • Sends a keydown, keypress/input, and keyup event for each character in the text.

                              Parameter selector

                              the selector for the element to type into. If there are multiple the first will be used.

                              Parameter text

                              text to type into the element

                              Parameter options

                              takes one option, delay, which sets the time to wait between key presses in milliseconds. Defaults to 0.

                              Returns

                              a promise that resolves when the typing is complete.

                              Remarks

                              To press a special key, like Control or ArrowDown, use Keyboard.press.

                              Example 1

                              await frame.type('#mytextarea', 'Hello'); // Types instantly
                              await frame.type('#mytextarea', 'World', {delay: 100}); // Types slower, like a user

                            method url

                            url: () => string;
                            • Returns

                              the frame's URL.

                            method waitFor

                            waitFor: (
                            selectorOrFunctionOrTimeout: string | number | Function,
                            options?: Record<string, unknown>,
                            ...args: SerializableOrJSHandle[]
                            ) => Promise<JSHandle | null>;
                            • Parameter selectorOrFunctionOrTimeout

                              a selector, predicate or timeout to wait for.

                              Parameter options

                              optional waiting parameters.

                              Parameter args

                              arguments to pass to pageFunction.

                              Remarks

                              This method behaves differently depending on the first parameter. If it's a string, it will be treated as a selector or xpath (if the string starts with //). This method then is a shortcut for Frame.waitForSelector or Frame.waitForXPath.

                              If the first argument is a function this method is a shortcut for Frame.waitForFunction.

                              If the first argument is a number, it's treated as a timeout in milliseconds and the method returns a promise which resolves after the timeout.

                              Deprecated

                              Don't use this method directly. Instead use the more explicit methods available: Frame.waitForSelector, Frame.waitForXPath, Frame.waitForFunction or Frame.waitForTimeout.

                            method waitForFunction

                            waitForFunction: (
                            pageFunction: Function | string,
                            options?: FrameWaitForFunctionOptions,
                            ...args: SerializableOrJSHandle[]
                            ) => Promise<JSHandle>;
                            • Parameter pageFunction

                              the function to evaluate in the frame context.

                              Parameter options

                              options to configure the polling method and timeout.

                              Parameter args

                              arguments to pass to the pageFunction.

                              Returns

                              the promise which resolve when the pageFunction returns a truthy value.

                              Remarks

                              Example 1

                              The waitForFunction can be used to observe viewport size change:

                              const puppeteer = require('puppeteer');
                              (async () => {
                              . const browser = await puppeteer.launch();
                              . const page = await browser.newPage();
                              . const watchDog = page.mainFrame().waitForFunction('window.innerWidth < 100');
                              . page.setViewport({width: 50, height: 50});
                              . await watchDog;
                              . await browser.close();
                              })();

                              To pass arguments from Node.js to the predicate of page.waitForFunction function:

                              const selector = '.foo';
                              await frame.waitForFunction(
                              selector => !!document.querySelector(selector),
                              {}, // empty options object
                              selector
                              );

                            method waitForNavigation

                            waitForNavigation: (options?: {
                            timeout?: number;
                            waitUntil?: PuppeteerLifeCycleEvent | PuppeteerLifeCycleEvent[];
                            }) => Promise<HTTPResponse | null>;
                            • Parameter options

                              options to configure when the navigation is consided finished.

                              Returns

                              a promise that resolves when the frame navigates to a new URL.

                              Remarks

                              This resolves when the frame navigates to a new URL. It is useful for when you run code which will indirectly cause the frame to navigate. Consider this example:

                              const [response] = await Promise.all([
                              // The navigation promise resolves after navigation has finished
                              frame.waitForNavigation(),
                              // Clicking the link will indirectly cause a navigation
                              frame.click('a.my-link'),
                              ]);

                              Usage of the History API to change the URL is considered a navigation.

                            method waitForSelector

                            waitForSelector: (
                            selector: string,
                            options?: WaitForSelectorOptions
                            ) => Promise<ElementHandle | null>;
                            • Parameter selector

                              the selector to wait for.

                              Parameter options

                              options to define if the element should be visible and how long to wait before timing out.

                              Returns

                              a promise which resolves when an element matching the selector string is added to the DOM.

                              Remarks

                              Wait for the selector to appear in page. If at the moment of calling the method the selector already exists, the method will return immediately. If the selector doesn't appear after the timeout milliseconds of waiting, the function will throw.

                              This method works across navigations.

                              Example 1

                              const puppeteer = require('puppeteer');
                              (async () => {
                              const browser = await puppeteer.launch();
                              const page = await browser.newPage();
                              let currentURL;
                              page.mainFrame()
                              .waitForSelector('img')
                              .then(() => console.log('First URL with image: ' + currentURL));
                              for (currentURL of ['https://example.com', 'https://google.com', 'https://bbc.com']) {
                              await page.goto(currentURL);
                              }
                              await browser.close();
                              })();

                            method waitForTimeout

                            waitForTimeout: (milliseconds: number) => Promise<void>;
                            • Causes your script to wait for the given number of milliseconds.

                              Parameter milliseconds

                              the number of milliseconds to wait.

                              Remarks

                              It's generally recommended to not wait for a number of seconds, but instead use Frame.waitForSelector, Frame.waitForXPath or Frame.waitForFunction to wait for exactly the conditions you want.

                              Example 1

                              Wait for 1 second:

                              await frame.waitForTimeout(1000);

                            method waitForXPath

                            waitForXPath: (
                            xpath: string,
                            options?: WaitForSelectorOptions
                            ) => Promise<ElementHandle | null>;
                            • Parameter xpath

                              the XPath expression to wait for.

                              Parameter options

                              options to configure the visiblity of the element and how long to wait before timing out.

                              Remarks

                              Wait for the xpath to appear in page. If at the moment of calling the method the xpath already exists, the method will return immediately. If the xpath doesn't appear after the timeout milliseconds of waiting, the function will throw.

                              For a code example, see the example for Frame.waitForSelector. That function behaves identically other than taking a CSS selector rather than an XPath.

                            class HTTPRequest

                            class HTTPRequest {}
                            • Represents an HTTP request sent by a page.

                              Remarks

                              Whenever the page sends a request, such as for a network resource, the following events are emitted by Puppeteer's page:

                              - request: emitted when the request is issued by the page. - requestfinished - emitted when the response body is downloaded and the request is complete.

                              If request fails at some point, then instead of requestfinished event the requestfailed event is emitted.

                              All of these events provide an instance of HTTPRequest representing the request that occurred:

                              page.on('request', request => ...)

                              NOTE: HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request will complete with requestfinished event.

                              If request gets a 'redirect' response, the request is successfully finished with the requestfinished event, and a new request is issued to a redirected url.

                              Modifiers

                              • @public

                            method abort

                            abort: (errorCode?: ErrorCode, priority?: number) => Promise<void>;
                            • Aborts a request.

                              Parameter errorCode

                              optional error code to provide.

                              Parameter priority

                              If provided, intercept is resolved using cooperative handling rules. Otherwise, intercept is resolved immediately.

                              Remarks

                              To use this, request interception should be enabled with Page.setRequestInterception. If it is not enabled, this method will throw an exception immediately.

                            method abortErrorReason

                            abortErrorReason: () => any;
                            • Returns

                              the most recent reason for aborting the request

                            method continue

                            continue: (
                            overrides?: ContinueRequestOverrides,
                            priority?: number
                            ) => Promise<void>;
                            • Continues request with optional request overrides.

                              Parameter overrides

                              optional overrides to apply to the request.

                              Parameter priority

                              If provided, intercept is resolved using cooperative handling rules. Otherwise, intercept is resolved immediately.

                              Remarks

                              To use this, request interception should be enabled with Page.setRequestInterception.

                              Exception is immediately thrown if the request interception is not enabled.

                              Example 1

                              await page.setRequestInterception(true);
                              page.on('request', request => {
                              // Override headers
                              const headers = Object.assign({}, request.headers(), {
                              foo: 'bar', // set "foo" header
                              origin: undefined, // remove "origin" header
                              });
                              request.continue({headers});
                              });

                            method continueRequestOverrides

                            continueRequestOverrides: () => ContinueRequestOverrides;
                            • Returns

                              the ContinueRequestOverrides that will be used if the interception is allowed to continue (ie, abort() and respond() aren't called).

                            method enqueueInterceptAction

                            enqueueInterceptAction: (
                            pendingHandler: () => void | PromiseLike<unknown>
                            ) => void;
                            • Adds an async request handler to the processing queue. Deferred handlers are not guaranteed to execute in any particular order, but they are guarnateed to resolve before the request interception is finalized.

                            method failure

                            failure: () => { errorText: string } | null;
                            • Access information about the request's failure.

                              Returns

                              null unless the request failed. If the request fails this can return an object with errorText containing a human-readable error message, e.g. net::ERR_FAILED. It is not guaranteeded that there will be failure text if the request fails.

                              Remarks

                              Example 1

                              Example of logging all failed requests:

                              page.on('requestfailed', request => {
                              console.log(request.url() + ' ' + request.failure().errorText);
                              });

                            method finalizeInterceptions

                            finalizeInterceptions: () => Promise<void>;
                            • Awaits pending interception handlers and then decides how to fulfill the request interception.

                            method frame

                            frame: () => Frame | null;
                            • Returns

                              the frame that initiated the request, or null if navigating to error pages.

                            method headers

                            headers: () => Record<string, string>;
                            • Returns

                              an object with HTTP headers associated with the request. All header names are lower-case.

                            method isNavigationRequest

                            isNavigationRequest: () => boolean;
                            • Returns

                              true if the request is the driver of the current frame's navigation.

                            method method

                            method: () => string;
                            • Returns

                              the method used (GET, POST, etc.)

                            method postData

                            postData: () => string | undefined;
                            • Returns

                              the request's post body, if any.

                            method redirectChain

                            redirectChain: () => HTTPRequest[];
                            • A redirectChain is a chain of requests initiated to fetch a resource.

                              Returns

                              the chain of requests - if a server responds with at least a single redirect, this chain will contain all requests that were redirected.

                              Remarks

                              redirectChain is shared between all the requests of the same chain.

                              For example, if the website http://example.com has a single redirect to https://example.com, then the chain will contain one request:

                              const response = await page.goto('http://example.com');
                              const chain = response.request().redirectChain();
                              console.log(chain.length); // 1
                              console.log(chain[0].url()); // 'http://example.com'

                              If the website https://google.com has no redirects, then the chain will be empty:

                              const response = await page.goto('https://google.com');
                              const chain = response.request().redirectChain();
                              console.log(chain.length); // 0

                            method resourceType

                            resourceType: () => any;
                            • Contains the request's resource type as it was perceived by the rendering engine.

                            method respond

                            respond: (
                            response: Partial<ResponseForRequest>,
                            priority?: number
                            ) => Promise<void>;
                            • Fulfills a request with the given response.

                              Parameter response

                              the response to fulfill the request with.

                              Parameter priority

                              If provided, intercept is resolved using cooperative handling rules. Otherwise, intercept is resolved immediately.

                              Remarks

                              To use this, request interception should be enabled with Page.setRequestInterception.

                              Exception is immediately thrown if the request interception is not enabled.

                              Example 1

                              An example of fulfilling all requests with 404 responses:

                              await page.setRequestInterception(true);
                              page.on('request', request => {
                              request.respond({
                              status: 404,
                              contentType: 'text/plain',
                              body: 'Not Found!'
                              });
                              });

                              NOTE: Mocking responses for dataURL requests is not supported. Calling request.respond for a dataURL request is a noop.

                            method response

                            response: () => HTTPResponse | null;
                            • Returns

                              A matching HTTPResponse object, or null if the response has not been received yet.

                            method responseForRequest

                            responseForRequest: () => Partial<ResponseForRequest>;
                            • Returns

                              The ResponseForRequest that gets used if the interception is allowed to respond (ie, abort() is not called).

                            method url

                            url: () => string;
                            • Returns

                              the URL of the request

                            class HTTPResponse

                            class HTTPResponse {}
                            • The HTTPResponse class represents responses which are received by the Page class.

                              Modifiers

                              • @public

                            method buffer

                            buffer: () => Promise<Buffer>;
                            • Returns

                              Promise which resolves to a buffer with response body.

                            method frame

                            frame: () => Frame | null;
                            • Returns

                              A Frame that initiated this response, or null if navigating to error pages.

                            method fromCache

                            fromCache: () => boolean;
                            • Returns

                              True if the response was served from either the browser's disk cache or memory cache.

                            method fromServiceWorker

                            fromServiceWorker: () => boolean;
                            • Returns

                              True if the response was served by a service worker.

                            method headers

                            headers: () => Record<string, string>;
                            • Returns

                              An object with HTTP headers associated with the response. All header names are lower-case.

                            method json

                            json: () => Promise<any>;
                            • Returns

                              Promise which resolves to a JSON representation of response body.

                              Remarks

                              This method will throw if the response body is not parsable via JSON.parse.

                            method ok

                            ok: () => boolean;
                            • Returns

                              True if the response was successful (status in the range 200-299).

                            method remoteAddress

                            remoteAddress: () => RemoteAddress;
                            • Returns

                              The IP address and port number used to connect to the remote server.

                            method request

                            request: () => HTTPRequest;

                            method securityDetails

                            securityDetails: () => SecurityDetails | null;
                            • Returns

                              SecurityDetails if the response was received over the secure connection, or null otherwise.

                            method status

                            status: () => number;
                            • Returns

                              The status code of the response (e.g., 200 for a success).

                            method statusText

                            statusText: () => string;
                            • Returns

                              The status text of the response (e.g. usually an "OK" for a success).

                            method text

                            text: () => Promise<string>;
                            • Returns

                              Promise which resolves to a text representation of response body.

                            method url

                            url: () => string;
                            • Returns

                              The URL of the response.

                            class JSCoverage

                            class JSCoverage {}
                            • Modifiers

                              • @public

                            constructor

                            constructor(client: CDPSession);

                              method start

                              start: (options?: {
                              resetOnNavigation?: boolean;
                              reportAnonymousScripts?: boolean;
                              includeRawScriptCoverage?: boolean;
                              }) => Promise<void>;

                                method stop

                                stop: () => Promise<JSCoverageEntry[]>;

                                  class JSHandle

                                  class JSHandle<HandleObjectType = unknown> {}
                                  • Represents an in-page JavaScript object. JSHandles can be created with the page.evaluateHandle method.

                                    Example 1

                                    const windowHandle = await page.evaluateHandle(() => window);

                                    JSHandle prevents the referenced JavaScript object from being garbage-collected unless the handle is disposed. JSHandles are auto- disposed when their origin frame gets navigated or the parent context gets destroyed.

                                    JSHandle instances can be used as arguments for Page.$eval, Page.evaluate, and Page.evaluateHandle.

                                    Modifiers

                                    • @public

                                  method asElement

                                  asElement: () => ElementHandle | null;
                                  • Returns

                                    Either null or the object handle itself, if the object handle is an instance of ElementHandle.

                                  method dispose

                                  dispose: () => Promise<void>;
                                  • Stops referencing the element handle, and resolves when the object handle is successfully disposed of.

                                  method evaluate

                                  evaluate: <T extends EvaluateFn<HandleObjectType>>(
                                  pageFunction: T | string,
                                  ...args: SerializableOrJSHandle[]
                                  ) => Promise<UnwrapPromiseLike<EvaluateFnReturnType<T>>>;
                                  • This method passes this handle as the first argument to pageFunction. If pageFunction returns a Promise, then handle.evaluate would wait for the promise to resolve and return its value.

                                    Example 1

                                    const tweetHandle = await page.$('.tweet .retweets');
                                    expect(await tweetHandle.evaluate(node => node.innerText)).toBe('10');

                                  method evaluateHandle

                                  evaluateHandle: <HandleType extends JSHandle<unknown> = JSHandle<unknown>>(
                                  pageFunction: EvaluateHandleFn,
                                  ...args: SerializableOrJSHandle[]
                                  ) => Promise<HandleType>;
                                  • This method passes this handle as the first argument to pageFunction.

                                    Remarks

                                    The only difference between jsHandle.evaluate and jsHandle.evaluateHandle is that jsHandle.evaluateHandle returns an in-page object (JSHandle).

                                    If the function passed to jsHandle.evaluateHandle returns a Promise, then evaluateHandle.evaluateHandle waits for the promise to resolve and returns its value.

                                    See Page.evaluateHandle for more details.

                                  method executionContext

                                  executionContext: () => ExecutionContext;
                                  • Returns the execution context the handle belongs to.

                                  method getProperties

                                  getProperties: () => Promise<Map<string, JSHandle>>;
                                  • The method returns a map with property names as keys and JSHandle instances for the property values.

                                    Example 1

                                    const listHandle = await page.evaluateHandle(() => document.body.children);
                                    const properties = await listHandle.getProperties();
                                    const children = [];
                                    for (const property of properties.values()) {
                                    const element = property.asElement();
                                    if (element)
                                    children.push(element);
                                    }
                                    children; // holds elementHandles to all children of document.body

                                  method getProperty

                                  getProperty: (propertyName: string) => Promise<JSHandle | undefined>;
                                  • Fetches a single property from the referenced object.

                                  method jsonValue

                                  jsonValue: <T = unknown>() => Promise<T>;
                                  • Returns

                                    Returns a JSON representation of the object.If the object has a toJSON function, it will not be called.

                                    Remarks

                                    The JSON is generated by running JSON.stringify on the object in page and consequent JSON.parse in puppeteer. **NOTE** The method throws if the referenced object is not stringifiable.

                                  method toString

                                  toString: () => string;
                                  • Returns a string representation of the JSHandle.

                                    Remarks

                                    Useful during debugging.

                                  class Keyboard

                                  class Keyboard {}
                                  • Keyboard provides an api for managing a virtual keyboard. The high level api is Keyboard.type, which takes raw characters and generates proper keydown, keypress/input, and keyup events on your page.

                                    Remarks

                                    For finer control, you can use Keyboard.down, Keyboard.up, and Keyboard.sendCharacter to manually fire events as if they were generated from a real keyboard.

                                    On MacOS, keyboard shortcuts like ⌘ A -> Select All do not work. See #1313.

                                    Example 1

                                    An example of holding down Shift in order to select and delete some text:

                                    await page.keyboard.type('Hello World!');
                                    await page.keyboard.press('ArrowLeft');
                                    await page.keyboard.down('Shift');
                                    for (let i = 0; i < ' World'.length; i++)
                                    await page.keyboard.press('ArrowLeft');
                                    await page.keyboard.up('Shift');
                                    await page.keyboard.press('Backspace');
                                    // Result text will end up saying 'Hello!'

                                    Example 2

                                    An example of pressing A

                                    await page.keyboard.down('Shift');
                                    await page.keyboard.press('KeyA');
                                    await page.keyboard.up('Shift');

                                    Modifiers

                                    • @public

                                  method down

                                  down: (key: KeyInput, options?: { text?: string }) => Promise<void>;
                                  • Dispatches a keydown event.

                                    Parameter key

                                    Name of key to press, such as ArrowLeft. See KeyInput for a list of all key names.

                                    Parameter options

                                    An object of options. Accepts text which, if specified, generates an input event with this text.

                                    Remarks

                                    If key is a single character and no modifier keys besides Shift are being held down, a keypress/input event will also generated. The text option can be specified to force an input event to be generated. If key is a modifier key, Shift, Meta, Control, or Alt, subsequent key presses will be sent with that modifier active. To release the modifier key, use Keyboard.up.

                                    After the key is pressed once, subsequent calls to Keyboard.down will have repeat set to true. To release the key, use Keyboard.up.

                                    Modifier keys DO influence Keyboard.down. Holding down Shift will type the text in upper case.

                                  method press

                                  press: (
                                  key: KeyInput,
                                  options?: { delay?: number; text?: string }
                                  ) => Promise<void>;
                                  • Shortcut for Keyboard.down and Keyboard.up.

                                    Parameter key

                                    Name of key to press, such as ArrowLeft. See KeyInput for a list of all key names.

                                    Parameter options

                                    An object of options. Accepts text which, if specified, generates an input event with this text. Accepts delay which, if specified, is the time to wait between keydown and keyup in milliseconds. Defaults to 0.

                                    Remarks

                                    If key is a single character and no modifier keys besides Shift are being held down, a keypress/input event will also generated. The text option can be specified to force an input event to be generated.

                                    Modifier keys DO effect Keyboard.press. Holding down Shift will type the text in upper case.

                                  method sendCharacter

                                  sendCharacter: (char: string) => Promise<void>;
                                  • Dispatches a keypress and input event. This does not send a keydown or keyup event.

                                    Parameter char

                                    Character to send into the page.

                                    Remarks

                                    Modifier keys DO NOT effect Keyboard.sendCharacter. Holding down Shift will not type the text in upper case.

                                    Example 1

                                    page.keyboard.sendCharacter('嗨');

                                  method type

                                  type: (text: string, options?: { delay?: number }) => Promise<void>;
                                  • Sends a keydown, keypress/input, and keyup event for each character in the text.

                                    Parameter text

                                    A text to type into a focused element.

                                    Parameter options

                                    An object of options. Accepts delay which, if specified, is the time to wait between keydown and keyup in milliseconds. Defaults to 0.

                                    Remarks

                                    To press a special key, like Control or ArrowDown, use Keyboard.press.

                                    Modifier keys DO NOT effect keyboard.type. Holding down Shift will not type the text in upper case.

                                    Example 1

                                    await page.keyboard.type('Hello'); // Types instantly
                                    await page.keyboard.type('World', {delay: 100}); // Types slower, like a user

                                  method up

                                  up: (key: KeyInput) => Promise<void>;
                                  • Dispatches a keyup event.

                                    Parameter key

                                    Name of key to release, such as ArrowLeft. See KeyInput for a list of all key names.

                                  class Mouse

                                  class Mouse {}
                                  • The Mouse class operates in main-frame CSS pixels relative to the top-left corner of the viewport.

                                    Remarks

                                    Every page object has its own Mouse, accessible with [page.mouse](#pagemouse).

                                    Example 1

                                    // Using ‘page.mouse’ to trace a 100x100 square.
                                    await page.mouse.move(0, 0);
                                    await page.mouse.down();
                                    await page.mouse.move(0, 100);
                                    await page.mouse.move(100, 100);
                                    await page.mouse.move(100, 0);
                                    await page.mouse.move(0, 0);
                                    await page.mouse.up();

                                    **Note**: The mouse events trigger synthetic MouseEvents. This means that it does not fully replicate the functionality of what a normal user would be able to do with their mouse.

                                    For example, dragging and selecting text is not possible using page.mouse. Instead, you can use the `DocumentOrShadowRoot.getSelection()` functionality implemented in the platform.

                                    Example 2

                                    For example, if you want to select all content between nodes:

                                    await page.evaluate((from, to) => {
                                    const selection = from.getRootNode().getSelection();
                                    const range = document.createRange();
                                    range.setStartBefore(from);
                                    range.setEndAfter(to);
                                    selection.removeAllRanges();
                                    selection.addRange(range);
                                    }, fromJSHandle, toJSHandle);

                                    If you then would want to copy-paste your selection, you can use the clipboard api:

                                    // The clipboard api does not allow you to copy, unless the tab is focused.
                                    await page.bringToFront();
                                    await page.evaluate(() => {
                                    // Copy the selected content to the clipboard
                                    document.execCommand('copy');
                                    // Obtain the content of the clipboard as a string
                                    return navigator.clipboard.readText();
                                    });

                                    **Note**: If you want access to the clipboard API, you have to give it permission to do so:

                                    await browser.defaultBrowserContext().overridePermissions(
                                    '<your origin>', ['clipboard-read', 'clipboard-write']
                                    );

                                    Modifiers

                                    • @public

                                  method click

                                  click: (
                                  x: number,
                                  y: number,
                                  options?: MouseOptions & { delay?: number }
                                  ) => Promise<void>;
                                  • Shortcut for mouse.move, mouse.down and mouse.up.

                                    Parameter x

                                    Horizontal position of the mouse.

                                    Parameter y

                                    Vertical position of the mouse.

                                    Parameter options

                                    Optional MouseOptions.

                                  method down

                                  down: (options?: MouseOptions) => Promise<void>;
                                  • Dispatches a mousedown event.

                                    Parameter options

                                    Optional MouseOptions.

                                  method drag

                                  drag: (start: Point, target: Point) => Promise<Protocol.Input.DragData>;
                                  • Dispatches a drag event.

                                    Parameter start

                                    starting point for drag

                                    Parameter target

                                    point to drag to

                                  method dragAndDrop

                                  dragAndDrop: (
                                  start: Point,
                                  target: Point,
                                  options?: { delay?: number }
                                  ) => Promise<void>;
                                  • Performs a drag, dragenter, dragover, and drop in sequence.

                                    Parameter target

                                    point to drag from

                                    Parameter target

                                    point to drop on

                                    Parameter options

                                    An object of options. Accepts delay which, if specified, is the time to wait between dragover and drop in milliseconds. Defaults to 0.

                                  method dragEnter

                                  dragEnter: (target: Point, data: any) => Promise<void>;
                                  • Dispatches a dragenter event.

                                    Parameter target

                                    point for emitting dragenter event

                                  method dragOver

                                  dragOver: (target: Point, data: any) => Promise<void>;
                                  • Dispatches a dragover event.

                                    Parameter target

                                    point for emitting dragover event

                                  method drop

                                  drop: (target: Point, data: any) => Promise<void>;
                                  • Performs a dragenter, dragover, and drop in sequence.

                                    Parameter target

                                    point to drop on

                                    Parameter data

                                    drag data containing items and operations mask

                                    Parameter options

                                    An object of options. Accepts delay which, if specified, is the time to wait between dragover and drop in milliseconds. Defaults to 0.

                                  method move

                                  move: (x: number, y: number, options?: { steps?: number }) => Promise<void>;
                                  • Dispatches a mousemove event.

                                    Parameter x

                                    Horizontal position of the mouse.

                                    Parameter y

                                    Vertical position of the mouse.

                                    Parameter options

                                    Optional object. If specified, the steps property sends intermediate mousemove events when set to 1 (default).

                                  method up

                                  up: (options?: MouseOptions) => Promise<void>;
                                  • Dispatches a mouseup event.

                                    Parameter options

                                    Optional MouseOptions.

                                  method wheel

                                  wheel: (options?: MouseWheelOptions) => Promise<void>;
                                  • Dispatches a mousewheel event.

                                    Parameter options

                                    Optional: MouseWheelOptions.

                                    Example 1

                                    An example of zooming into an element:

                                    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 })

                                  class Page

                                  class Page extends EventEmitter {}
                                  • Page provides methods to interact with a single tab or extension background page in Chromium.

                                    Remarks

                                    One Browser instance might have multiple Page instances.

                                    Example 1

                                    This example creates a page, navigates it to a URL, and then * saves a screenshot:

                                    const puppeteer = require('puppeteer');
                                    (async () => {
                                    const browser = await puppeteer.launch();
                                    const page = await browser.newPage();
                                    await page.goto('https://example.com');
                                    await page.screenshot({path: 'screenshot.png'});
                                    await browser.close();
                                    })();

                                    The Page class extends from Puppeteer's EventEmitter class and will emit various events which are documented in the PageEmittedEvents enum.

                                    Example 2

                                    This example logs a message for a single page load event:

                                    page.once('load', () => console.log('Page loaded!'));

                                    To unsubscribe from events use the off method:

                                    function logRequest(interceptedRequest) {
                                    console.log('A request was made:', interceptedRequest.url());
                                    }
                                    page.on('request', logRequest);
                                    // Sometime later...
                                    page.off('request', logRequest);

                                    Modifiers

                                    • @public

                                  property accessibility

                                  readonly accessibility: Accessibility;

                                    property coverage

                                    readonly coverage: Coverage;

                                      property keyboard

                                      readonly keyboard: Keyboard;

                                        property mouse

                                        readonly mouse: Mouse;

                                          property touchscreen

                                          readonly touchscreen: Touchscreen;

                                            property tracing

                                            readonly tracing: Tracing;

                                              method $

                                              $: <T extends Element = Element>(
                                              selector: string
                                              ) => Promise<ElementHandle<T> | null>;
                                              • Runs document.querySelector within the page. If no element matches the selector, the return value resolves to null.

                                                Parameter selector

                                                A selector to query page for selector to query page for.

                                                Remarks

                                                Shortcut for Page.mainFrame().$(selector).

                                              method $$

                                              $$: <T extends Element = Element>(
                                              selector: string
                                              ) => Promise<Array<ElementHandle<T>>>;
                                              • The method runs document.querySelectorAll within the page. If no elements match the selector, the return value resolves to [].

                                                Parameter selector

                                                A selector to query page for

                                                Remarks

                                                Shortcut for Page.mainFrame().$$(selector).

                                              method $$eval

                                              $$eval: <ReturnType>(
                                              selector: string,
                                              pageFunction: (
                                              elements: Element[],
                                              ...args: unknown[]
                                              ) => ReturnType | Promise<ReturnType>,
                                              ...args: SerializableOrJSHandle[]
                                              ) => Promise<WrapElementHandle<ReturnType>>;
                                              • This method runs Array.from(document.querySelectorAll(selector)) within the page and passes the result as the first argument to the pageFunction.

                                                Parameter selector

                                                the selector to query for

                                                Parameter pageFunction

                                                the function to be evaluated in the page context. Will be passed the result of Array.from(document.querySelectorAll(selector)) as its first argument.

                                                Parameter args

                                                any additional arguments to pass through to pageFunction.

                                                Returns

                                                The result of calling pageFunction. If it returns an element it is wrapped in an ElementHandle, else the raw value itself is returned.

                                                Remarks

                                                If pageFunction returns a promise $$eval will wait for the promise to resolve and then return its value.

                                                Example 1

                                                // get the amount of divs on the page
                                                const divCount = await page.$$eval('div', divs => divs.length);
                                                // get the text content of all the `.options` elements:
                                                const options = await page.$$eval('div > span.options', options => {
                                                return options.map(option => option.textContent)
                                                });

                                                If you are using TypeScript, you may have to provide an explicit type to the first argument of the pageFunction. By default it is typed as Element[], but you may need to provide a more specific sub-type:

                                                Example 2

                                                // if you don't provide HTMLInputElement here, TS will error
                                                // as `value` is not on `Element`
                                                await page.$$eval('input', (elements: HTMLInputElement[]) => {
                                                return elements.map(e => e.value);
                                                });

                                                The compiler should be able to infer the return type from the pageFunction you provide. If it is unable to, you can use the generic type to tell the compiler what return type you expect from $$eval:

                                                Example 3

                                                // The compiler can infer the return type in this case, but if it can't
                                                // or if you want to be more explicit, provide it as the generic type.
                                                const allInputValues = await page.$$eval<string[]>(
                                                'input', (elements: HTMLInputElement[]) => elements.map(e => e.textContent)
                                                );

                                              method $eval

                                              $eval: <ReturnType>(
                                              selector: string,
                                              pageFunction: (
                                              element: Element,
                                              ...args: unknown[]
                                              ) => ReturnType | Promise<ReturnType>,
                                              ...args: SerializableOrJSHandle[]
                                              ) => Promise<WrapElementHandle<ReturnType>>;
                                              • This method runs document.querySelector within the page and passes the result as the first argument to the pageFunction.

                                                Parameter selector

                                                the selector to query for

                                                Parameter pageFunction

                                                the function to be evaluated in the page context. Will be passed the result of document.querySelector(selector) as its first argument.

                                                Parameter args

                                                any additional arguments to pass through to pageFunction.

                                                Returns

                                                The result of calling pageFunction. If it returns an element it is wrapped in an ElementHandle, else the raw value itself is returned.

                                                Remarks

                                                If no element is found matching selector, the method will throw an error.

                                                If pageFunction returns a promise $eval will wait for the promise to resolve and then return its value.

                                                Example 1

                                                const searchValue = await page.$eval('#search', el => el.value);
                                                const preloadHref = await page.$eval('link[rel=preload]', el => el.href);
                                                const html = await page.$eval('.main-container', el => el.outerHTML);

                                                If you are using TypeScript, you may have to provide an explicit type to the first argument of the pageFunction. By default it is typed as Element, but you may need to provide a more specific sub-type:

                                                Example 2

                                                // if you don't provide HTMLInputElement here, TS will error
                                                // as `value` is not on `Element`
                                                const searchValue = await page.$eval('#search', (el: HTMLInputElement) => el.value);

                                                The compiler should be able to infer the return type from the pageFunction you provide. If it is unable to, you can use the generic type to tell the compiler what return type you expect from $eval:

                                                Example 3

                                                // The compiler can infer the return type in this case, but if it can't
                                                // or if you want to be more explicit, provide it as the generic type.
                                                const searchValue = await page.$eval<string>(
                                                '#search', (el: HTMLInputElement) => el.value
                                                );

                                              method $x

                                              $x: (expression: string) => Promise<ElementHandle[]>;
                                              • The method evaluates the XPath expression relative to the page document as its context node. If there are no such elements, the method resolves to an empty array.

                                                Parameter expression

                                                Expression to evaluate

                                                Remarks

                                                Shortcut for Page.mainFrame().$x(expression).

                                              method addScriptTag

                                              addScriptTag: (options: {
                                              url?: string;
                                              path?: string;
                                              content?: string;
                                              type?: string;
                                              id?: string;
                                              }) => Promise<ElementHandle>;
                                              • Adds a <script> tag into the page with the desired URL or content.

                                                Returns

                                                Promise which resolves to the added tag when the script's onload fires or when the script content was injected into frame.

                                                Remarks

                                                Shortcut for page.mainFrame().addScriptTag(options).

                                              method addStyleTag

                                              addStyleTag: (options: {
                                              url?: string;
                                              path?: string;
                                              content?: string;
                                              }) => Promise<ElementHandle>;
                                              • Adds a <link rel="stylesheet"> tag into the page with the desired URL or a <style type="text/css"> tag with the content.

                                                Returns

                                                Promise which resolves to the added tag when the stylesheet's onload fires or when the CSS content was injected into frame.

                                              method authenticate

                                              authenticate: (credentials: Credentials) => Promise<void>;
                                              • Provide credentials for HTTP authentication.

                                                Remarks

                                                To disable authentication, pass null.

                                              method bringToFront

                                              bringToFront: () => Promise<void>;
                                              • Brings page to front (activates tab).

                                              method browser

                                              browser: () => Browser;
                                              • Get the browser the page belongs to.

                                              method browserContext

                                              browserContext: () => BrowserContext;
                                              • Get the browser context that the page belongs to.

                                              method click

                                              click: (
                                              selector: string,
                                              options?: { delay?: number; button?: MouseButton; clickCount?: number }
                                              ) => Promise<void>;
                                              • This method fetches an element with selector, scrolls it into view if needed, and then uses Page.mouse to click in the center of the element. If there's no element matching selector, the method throws an error.

                                                Parameter selector

                                                A selector to search for element to click. If there are multiple elements satisfying the selector, the first will be clicked

                                                Parameter options

                                                Object

                                                Returns

                                                Promise which resolves when the element matching selector is successfully clicked. The Promise will be rejected if there is no element matching selector.

                                                Remarks

                                                Bear in mind that if click() triggers a navigation event and there's a separate page.waitForNavigation() promise to be resolved, you may end up with a race condition that yields unexpected results. The correct pattern for click and wait for navigation is the following:

                                                const [response] = await Promise.all([
                                                page.waitForNavigation(waitOptions),
                                                page.click(selector, clickOptions),
                                                ]);

                                                Shortcut for page.mainFrame().click(selector[, options]).

                                              method close

                                              close: (options?: { runBeforeUnload?: boolean }) => Promise<void>;

                                                method content

                                                content: () => Promise<string>;

                                                  method cookies

                                                  cookies: (...urls: string[]) => Promise<Protocol.Network.Cookie[]>;
                                                  • If no URLs are specified, this method returns cookies for the current page URL. If URLs are specified, only cookies for those URLs are returned.

                                                  method createPDFStream

                                                  createPDFStream: (options?: PDFOptions) => Promise<Readable>;
                                                  • Generatees a PDF of the page with the print CSS media type.

                                                    Parameter options

                                                    options for generating the PDF.

                                                    Remarks

                                                    NOTE: PDF generation is only supported in Chrome headless mode.

                                                    To generate a PDF with the screen media type, call `page.emulateMediaType('screen')` before calling page.pdf().

                                                    By default, page.pdf() generates a pdf with modified colors for printing. Use the `-webkit-print-color-adjust` property to force rendering of exact colors.

                                                  method deleteCookie

                                                  deleteCookie: (
                                                  ...cookies: Protocol.Network.DeleteCookiesRequest[]
                                                  ) => Promise<void>;

                                                    method emulate

                                                    emulate: (options: { viewport: Viewport; userAgent: string }) => Promise<void>;
                                                    • Emulates given device metrics and user agent. This method is a shortcut for calling two methods: Page.setUserAgent and Page.setViewport To aid emulation, Puppeteer provides a list of device descriptors that can be obtained via the Puppeteer.devices page.emulate will resize the page. A lot of websites don't expect phones to change size, so you should emulate before navigating to the page.

                                                      Remarks

                                                      List of all available devices is available in the source code: src/common/DeviceDescriptors.ts.

                                                      Example 1

                                                      const puppeteer = require('puppeteer');
                                                      const iPhone = puppeteer.devices['iPhone 6'];
                                                      (async () => {
                                                      const browser = await puppeteer.launch();
                                                      const page = await browser.newPage();
                                                      await page.emulate(iPhone);
                                                      await page.goto('https://www.google.com');
                                                      // other actions...
                                                      await browser.close();
                                                      })();

                                                    method emulateCPUThrottling

                                                    emulateCPUThrottling: (factor: number | null) => Promise<void>;

                                                      method emulateIdleState

                                                      emulateIdleState: (overrides?: {
                                                      isUserActive: boolean;
                                                      isScreenUnlocked: boolean;
                                                      }) => Promise<void>;
                                                      • Emulates the idle state. If no arguments set, clears idle state emulation.

                                                        Parameter overrides

                                                        Mock idle state. If not set, clears idle overrides

                                                        Example 1

                                                        // set idle emulation
                                                        await page.emulateIdleState({isUserActive: true, isScreenUnlocked: false});
                                                        // do some checks here
                                                        ...
                                                        // clear idle emulation
                                                        await page.emulateIdleState();

                                                      method emulateMediaFeatures

                                                      emulateMediaFeatures: (features?: MediaFeature[]) => Promise<void>;
                                                      • Parameter features

                                                        <?Array<Object>> Given an array of media feature objects, emulates CSS media features on the page. Each media feature object must have the following properties:

                                                        Example 1

                                                        await page.emulateMediaFeatures([
                                                        { name: 'prefers-color-scheme', value: 'dark' },
                                                        ]);
                                                        await page.evaluate(() => matchMedia('(prefers-color-scheme: dark)').matches);
                                                        // → true
                                                        await page.evaluate(() => matchMedia('(prefers-color-scheme: light)').matches);
                                                        // → false
                                                        await page.emulateMediaFeatures([
                                                        { name: 'prefers-reduced-motion', value: 'reduce' },
                                                        ]);
                                                        await page.evaluate(
                                                        () => matchMedia('(prefers-reduced-motion: reduce)').matches
                                                        );
                                                        // → true
                                                        await page.evaluate(
                                                        () => matchMedia('(prefers-reduced-motion: no-preference)').matches
                                                        );
                                                        // → false
                                                        await page.emulateMediaFeatures([
                                                        { name: 'prefers-color-scheme', value: 'dark' },
                                                        { name: 'prefers-reduced-motion', value: 'reduce' },
                                                        ]);
                                                        await page.evaluate(() => matchMedia('(prefers-color-scheme: dark)').matches);
                                                        // → true
                                                        await page.evaluate(() => matchMedia('(prefers-color-scheme: light)').matches);
                                                        // → false
                                                        await page.evaluate(
                                                        () => matchMedia('(prefers-reduced-motion: reduce)').matches
                                                        );
                                                        // → true
                                                        await page.evaluate(
                                                        () => matchMedia('(prefers-reduced-motion: no-preference)').matches
                                                        );
                                                        // → false
                                                        await page.emulateMediaFeatures([{ name: 'color-gamut', value: 'p3' }]);
                                                        await page.evaluate(() => matchMedia('(color-gamut: srgb)').matches);
                                                        // → true
                                                        await page.evaluate(() => matchMedia('(color-gamut: p3)').matches);
                                                        // → true
                                                        await page.evaluate(() => matchMedia('(color-gamut: rec2020)').matches);
                                                        // → false

                                                      method emulateMediaType

                                                      emulateMediaType: (type?: string) => Promise<void>;
                                                      • Parameter type

                                                        Changes the CSS media type of the page. The only allowed values are screen, print and null. Passing null disables CSS media emulation.

                                                        Example 1

                                                        await page.evaluate(() => matchMedia('screen').matches);
                                                        // → true
                                                        await page.evaluate(() => matchMedia('print').matches);
                                                        // → false
                                                        await page.emulateMediaType('print');
                                                        await page.evaluate(() => matchMedia('screen').matches);
                                                        // → false
                                                        await page.evaluate(() => matchMedia('print').matches);
                                                        // → true
                                                        await page.emulateMediaType(null);
                                                        await page.evaluate(() => matchMedia('screen').matches);
                                                        // → true
                                                        await page.evaluate(() => matchMedia('print').matches);
                                                        // → false

                                                      method emulateNetworkConditions

                                                      emulateNetworkConditions: (
                                                      networkConditions: NetworkConditions | null
                                                      ) => Promise<void>;
                                                      • Parameter networkConditions

                                                        Passing null disables network condition emulation.

                                                        Remarks

                                                        NOTE: This does not affect WebSockets and WebRTC PeerConnections (see https://crbug.com/563644). To set the page offline, you can use [page.setOfflineMode(enabled)](#pagesetofflinemodeenabled).

                                                        Example 1

                                                        const puppeteer = require('puppeteer');
                                                        const slow3G = puppeteer.networkConditions['Slow 3G'];
                                                        (async () => {
                                                        const browser = await puppeteer.launch();
                                                        const page = await browser.newPage();
                                                        await page.emulateNetworkConditions(slow3G);
                                                        await page.goto('https://www.google.com');
                                                        // other actions...
                                                        await browser.close();
                                                        })();

                                                      method emulateTimezone

                                                      emulateTimezone: (timezoneId?: string) => Promise<void>;
                                                      • Parameter timezoneId

                                                        Changes the timezone of the page. See ICU’s metaZones.txt for a list of supported timezone IDs. Passing null disables timezone emulation.

                                                      method emulateVisionDeficiency

                                                      emulateVisionDeficiency: (type?: any) => Promise<void>;
                                                      • Simulates the given vision deficiency on the page.

                                                        Parameter type

                                                        the type of deficiency to simulate, or 'none' to reset.

                                                        Example 1

                                                        const puppeteer = require('puppeteer');
                                                        (async () => {
                                                        const browser = await puppeteer.launch();
                                                        const page = await browser.newPage();
                                                        await page.goto('https://v8.dev/blog/10-years');
                                                        await page.emulateVisionDeficiency('achromatopsia');
                                                        await page.screenshot({ path: 'achromatopsia.png' });
                                                        await page.emulateVisionDeficiency('deuteranopia');
                                                        await page.screenshot({ path: 'deuteranopia.png' });
                                                        await page.emulateVisionDeficiency('blurredVision');
                                                        await page.screenshot({ path: 'blurred-vision.png' });
                                                        await browser.close();
                                                        })();

                                                      method evaluate

                                                      evaluate: <T extends EvaluateFn<any>>(
                                                      pageFunction: T,
                                                      ...args: SerializableOrJSHandle[]
                                                      ) => Promise<UnwrapPromiseLike<EvaluateFnReturnType<T>>>;
                                                      • Parameter pageFunction

                                                        a function that is run within the page

                                                        Parameter args

                                                        arguments to be passed to the pageFunction

                                                        Returns

                                                        the return value of pageFunction.

                                                        Remarks

                                                        Evaluates a function in the page's context and returns the result.

                                                        If the function passed to page.evaluteHandle returns a Promise, the function will wait for the promise to resolve and return its value.

                                                        Example 1

                                                        const result = await frame.evaluate(() => {
                                                        return Promise.resolve(8 * 7);
                                                        });
                                                        console.log(result); // prints "56"

                                                        You can pass a string instead of a function (although functions are recommended as they are easier to debug and use with TypeScript):

                                                        Example 2

                                                        const aHandle = await page.evaluate('1 + 2');

                                                        To get the best TypeScript experience, you should pass in as the generic the type of pageFunction:

                                                        const aHandle = await page.evaluate<() => number>(() => 2);

                                                        Example 3

                                                        ElementHandle instances (including JSHandles) can be passed as arguments to the pageFunction:

                                                        const bodyHandle = await page.$('body');
                                                        const html = await page.evaluate(body => body.innerHTML, bodyHandle);
                                                        await bodyHandle.dispose();

                                                      method evaluateHandle

                                                      evaluateHandle: <HandlerType extends JSHandle<unknown> = JSHandle<unknown>>(
                                                      pageFunction: EvaluateHandleFn,
                                                      ...args: SerializableOrJSHandle[]
                                                      ) => Promise<HandlerType>;
                                                      • Parameter pageFunction

                                                        a function that is run within the page

                                                        Parameter args

                                                        arguments to be passed to the pageFunction

                                                        Remarks

                                                        The only difference between page.evaluate and page.evaluateHandle is that evaluateHandle will return the value wrapped in an in-page object.

                                                        If the function passed to page.evaluteHandle returns a Promise, the function will wait for the promise to resolve and return its value.

                                                        You can pass a string instead of a function (although functions are recommended as they are easier to debug and use with TypeScript):

                                                        Example 1

                                                        const aHandle = await page.evaluateHandle('document')

                                                        Example 2

                                                        JSHandle instances can be passed as arguments to the pageFunction:

                                                        const aHandle = await page.evaluateHandle(() => document.body);
                                                        const resultHandle = await page.evaluateHandle(body => body.innerHTML, aHandle);
                                                        console.log(await resultHandle.jsonValue());
                                                        await resultHandle.dispose();

                                                        Most of the time this function returns a JSHandle, but if pageFunction returns a reference to an element, you instead get an ElementHandle back:

                                                        Example 3

                                                        const button = await page.evaluateHandle(() => document.querySelector('button'));
                                                        // can call `click` because `button` is an `ElementHandle`
                                                        await button.click();

                                                        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:

                                                        const button = await page.evaluateHandle<ElementHandle>(...);

                                                      method evaluateOnNewDocument

                                                      evaluateOnNewDocument: (
                                                      pageFunction: Function | string,
                                                      ...args: unknown[]
                                                      ) => Promise<void>;
                                                      • 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. In this case, the function is invoked in the context of the newly attached frame.

                                                        The function is invoked after the document was created but before any of its scripts were run. This is useful to amend the JavaScript environment, e.g. to seed Math.random.

                                                        Parameter pageFunction

                                                        Function to be evaluated in browser context

                                                        Parameter args

                                                        Arguments to pass to pageFunction

                                                        Example 1

                                                        An example of overriding the navigator.languages property before the page loads:

                                                        // preload.js
                                                        // overwrite the `languages` property to use a custom getter
                                                        Object.defineProperty(navigator, 'languages', {
                                                        get: function () {
                                                        return ['en-US', 'en', 'bn'];
                                                        },
                                                        });
                                                        // In your puppeteer script, assuming the preload.js file is
                                                        in same folder of our script
                                                        const preloadFile = fs.readFileSync('./preload.js', 'utf8');
                                                        await page.evaluateOnNewDocument(preloadFile);

                                                      method exposeFunction

                                                      exposeFunction: (name: string, puppeteerFunction: Function) => Promise<void>;
                                                      • The method adds a function called name on the page's window object. When called, the function executes puppeteerFunction in node.js and returns a Promise which resolves to the return value of puppeteerFunction.

                                                        If the puppeteerFunction returns a Promise, it will be awaited.

                                                        NOTE: Functions installed via page.exposeFunction survive navigations.

                                                        Parameter name

                                                        Name of the function on the window object

                                                        Parameter puppeteerFunction

                                                        Callback function which will be called in Puppeteer's context.

                                                        Example 1

                                                        An example of adding an md5 function into the page:

                                                        const puppeteer = require('puppeteer');
                                                        const crypto = require('crypto');
                                                        (async () => {
                                                        const browser = await puppeteer.launch();
                                                        const page = await browser.newPage();
                                                        page.on('console', (msg) => console.log(msg.text()));
                                                        await page.exposeFunction('md5', (text) =>
                                                        crypto.createHash('md5').update(text).digest('hex')
                                                        );
                                                        await page.evaluate(async () => {
                                                        // use window.md5 to compute hashes
                                                        const myString = 'PUPPETEER';
                                                        const myHash = await window.md5(myString);
                                                        console.log(`md5 of ${myString} is ${myHash}`);
                                                        });
                                                        await browser.close();
                                                        })();

                                                        An example of adding a window.readfile function into the page:

                                                        const puppeteer = require('puppeteer');
                                                        const fs = require('fs');
                                                        (async () => {
                                                        const browser = await puppeteer.launch();
                                                        const page = await browser.newPage();
                                                        page.on('console', (msg) => console.log(msg.text()));
                                                        await page.exposeFunction('readfile', async (filePath) => {
                                                        return new Promise((resolve, reject) => {
                                                        fs.readFile(filePath, 'utf8', (err, text) => {
                                                        if (err) reject(err);
                                                        else resolve(text);
                                                        });
                                                        });
                                                        });
                                                        await page.evaluate(async () => {
                                                        // use window.readfile to read contents of a file