PhantomJsCloud Automation API
    Preparing search index...

    Class Page

    Methods to interact with a single page (tab) in the Chrome browser.

    This is usable globally from your script (no need to construct a new instance)

    Example showing basic automaton:

    // every time the domLoaded event triggers 
    * page.on("domcontentloaded",()=>{
    * //scrolls the element into view then clicks it with the left mouse button
    * page.click("#btn2");
    * });

    Hierarchy

    • _PlatformObjBinding
      • Page
    Index
    accessibility: 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.

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

    see Accessibility for more details

    coverage: Coverage = ...
    diagnostics: Diagnostics = ...

    helpers to troubleshoot automation issues.

    see Diagnostics for more information

    keyboard: Keyboard = ...

    automate keyboard presses.

    see Keyboard for more information

    meta: Meta = ...

    contains helpers for operating beyond the current page. such as get/set values between page navigations, and logging details that will be stored in your response output.

    See the Meta documentation for more details.

    //store a value that can be read by other pages, and is also available in the response output
    page.meta.store.set("answer",42);
    mouse: Mouse = ...

    contains functions for controlling the mouse on the page. Clicking, moving, etc. Also see Touchscreen and Keyboard.

    See the Mouse documentation for more details.

    //perform a mouse click
    page.mouse.click(200,11);
    on: <K extends keyof PageOnEvents>(
        eventName: K,
        handler: PageOnEvents[K],
    ) => this = ...

    The page.on() allows you to attach to events of the page.

    For example:

    page.on('load', () => page.meta.log('Page loaded!'));
    

    For details of all events you can hook, please see PageOnEvents

    Type Declaration

      • <K extends keyof PageOnEvents>(eventName: K, handler: PageOnEvents[K]): this
      • Type Parameters

        Parameters

        • eventName: K

          For syntax and details of all events you can hook, please see PageOnEvents

        • handler: PageOnEvents[K]

          For syntax and details of all events you can hook, please see PageOnEvents

        Returns this

    render: Render = ...
    touchscreen: Touchscreen = ...

    automate taps on a touch screen.

    See Touchscreen for more information

    tracing: Tracing = ...

    perform performance traces.

    • Runs document.querySelector in the main frame and returns the first matching element as an :class, or null when nothing matches.

      Like the other main-frame calls, it waits until pjsc's own navigation to the request url has finished.

      const button = await page.$("#submit");
      if (button) await button.click();

      Parameters

      • selector: string

        a CSS selector

      Returns Promise<ElementHandle>

    • Runs document.querySelectorAll in the main frame and returns every matching element as an :class (an empty array when nothing matches).

      const rows = await page.$$("table tr");
      page.meta.log("rows", rows.length);

      Parameters

      • selector: string

        a CSS selector

      Returns Promise<ElementHandle[]>

      • selector <string> A selector to query page for
      • pageFunction <function(Array<Element<)< Function to be evaluated in browser context
      • ...args <...Serializable|JSHandle< Arguments to pass to pageFunction
      • returns: <Promise<Serializable>> Promise which resolves to the return value of pageFunction

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

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

      Examples:

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

      Type Parameters

      • T

      Parameters

      • selector: string
      • pageFunction: (elms: Element[], ...args: any[]) => T | Promise<T>
      • ...args: any[]

      Returns Promise<any>

      • selector <string> A selector to query page for
      • pageFunction <function(Array<Element<)< Function to be evaluated in browser context
      • ...args <...Serializable|JSHandle< Arguments to pass to pageFunction
      • returns: <Promise<Serializable>> Promise which resolves to the return value of pageFunction

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

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

      Examples:

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

      Type Parameters

      • T

      Parameters

      • options: { selector: string } & FrameExecOptions
      • pageFunction: (elms: Element[], ...args: any[]) => T | Promise<T>
      • ...args: any[]

      Returns Promise<any>

      • selector <string> A selector to query page for
      • pageFunction <function(Element)> Function to be evaluated in browser context
      • ...args <...Serializable|JSHandle> Arguments to pass to pageFunction
      • returns: <Promise<Serializable>> Promise which resolves to the return value of pageFunction

      This method runs document.querySelector within the page 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 page.$eval would wait for the promise to resolve and return its value.

      Examples:

      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', e => e.outerHTML);

      Type Parameters

      • T

      Parameters

      • selector: string
      • pageFunction: (elm: Element, ...args: any[]) => T | Promise<T>
      • ...args: any[]

      Returns Promise<any>

      • selector <string> A selector to query page for
      • pageFunction <function(Element)> Function to be evaluated in browser context
      • ...args <...Serializable|JSHandle> Arguments to pass to pageFunction
      • returns: <Promise<Serializable>> Promise which resolves to the return value of pageFunction

      This method runs document.querySelector within the page 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 page.$eval would wait for the promise to resolve and return its value.

      Examples:

      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', e => e.outerHTML);

      Type Parameters

      • T

      Parameters

      • options: { selector: string } & FrameExecOptions
      • pageFunction: (elm: Element, ...args: any[]) => T | Promise<T>
      • ...args: any[]

      Returns Promise<any>

      • options <Object> - url <string> URL of a script to be added. - content <string> Raw JavaScript content to be injected into frame. - type <string> Script type. Use 'module' in order to load a Javascript ES6 module. See script for more details.
      • returns: {Promise{ElementHandle}} which resolves to the added tag when the script's onload fires or when the script content was injected into frame.

      Adds a <script> tag into the page with the desired url or content.

      Parameters

      Returns Promise<void>

      • options <Object> - url <string> URL of the <link< tag. - content <string> Raw CSS content to be injected into frame.
      • returns: <Promise<ElementHandle>> which resolves to the added tag when the stylesheet's onload fires or when the CSS content was injected into frame.

      Adds a <link rel="stylesheet" > tag into the page with the desired url or a <style type="text/css"> tag with the content.

      Parameters

      Returns Promise<void>

      • credentialOptions <?Object< - username <string> - password <string>
      • returns: <Promise>

      Provide credentials for HTTP authentication. On a render whose proxy has a login (pjsc's built-in proxy, the geo proxy, or a custom proxy with auth), they answer only the website's login prompts and the proxy's login stays; on other renders they answer every login prompt, as in Puppeteer.

      To clear the credentials, pass null.

      Parameters

      • options: { password: string; username: string }

      Returns Promise<void>

    • Brings page to front (activates tab).

      Returns Promise<void>

      • selector <string> A selector to search for element to click. If there are multiple elements satisfying the selector, the first will be clicked.
      • options <Object> - button <"left"|"right"|"middle"< Defaults to left. - clickCount <number> defaults to 1. See UIEvent.detail. - delay <number> Time to wait between mousedown and mouseup in milliseconds. Defaults to 0.
      • returns: <Promise> Promise which resolves when the element matching selector is successfully clicked. The Promise will be rejected if there is no element matching selector.

      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.

      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),
      ]);

      Parameters

      Returns Promise<void>

    • Very similar to Render.content but instead of storing the html/text to output, it is returned by this function.

      Parameters

      Returns Promise<string>

      a string containing html/plainText.

      • ...urls <...string>
      • returns: <Promise<Array<Object>>> - name <string> - value <string> - domain <string> - path <string> - expires <number> Unix time in seconds. - size <number> - httpOnly <boolean> - secure <boolean> - session <boolean> - sameSite <"Strict"|"Lax"|"Extended"|"None">

      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.

      Parameters

      • ...urls: string[]

      Returns Promise<Cookie[]>

      • ...cookies <...Object> - name <string> required - url <string> - domain <string> - path <string>
      • returns: <Promise>

      Parameters

      Returns Promise<void>

    • call this to signal that your request is done and the results can be returned to you. Especially useful in conjunction with Page.manualWait but can also be used to finish execution earlier than normal (not wait for ajax scripts, etc).

      Parameters

      • code: number = 200

        allows you to customize the value of content.statusCode in the output JSON and response headers.

        Note: this does not change the API's response code. It lets you customize a "content" code when parsing the results.

      • reason: string = "normal"

        allows you to customize the value of content.doneDetail in the output JSON and response headers

      Returns Promise<void>

      • options <Object> - viewport <Object> - width <number> page width in pixels. - height <number> page height in pixels. - deviceScaleFactor <number> Specify device scale factor (can be thought of as dpr). Defaults to 1. - isMobile <boolean> Whether the meta viewport tag is taken into account. Defaults to false. - hasTouch<boolean> Specifies if viewport supports touch events. Defaults to false - isLandscape <boolean> Specifies if viewport is in landscape mode. Defaults to false. - userAgent <string>
      • returns: <Promise>

      Emulates given device metrics and user agent. This method is a shortcut for calling two methods:

      page.setUserAgent(userAgent)
      page.setViewport(viewport)

      NOTE: 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.

      Parameters

      Returns Promise<void>

    • Slows the page's CPU by factor (1 = no throttling); null ends the throttling.

      Parameters

      • factor: number

        slowdown factor, at least 1

      Returns Promise<void>

    • Makes the page behave as if it had focus (document.hasFocus(), focus events), or ends that emulation.

      Parameters

      • enabled: boolean

        true emulates a focused page

      Returns Promise<void>

    • Emulates the user idle state; no argument ends the emulation.

      Parameters

      • Optionaloverrides: { isScreenUnlocked: boolean; isUserActive: boolean }

        isUserActive, isScreenUnlocked

      Returns Promise<void>

    • Parameters

      • mediaType: "screen" | "print"

      Returns Promise<void>

      use Page.emulateMediaType instead

    • Given an array of media feature objects, emulates CSS media features on the page. Passing null resets all.

      Parameters

      Returns Promise<void>

      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.evaluate(() => matchMedia('(prefers-color-scheme: no-preference)').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-color-scheme: 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-color-scheme: no-preference)').matches));
      // → false
      await page.evaluate(() => matchMedia('(prefers-reduced-motion: reduce)').matches));
      // → true
      await page.evaluate(() => matchMedia('(prefers-color-scheme: no-preference)').matches));
      // → false
      • mediaType <?string> Changes the CSS media type of the page. The only allowed values are 'screen', 'print' and null. Passing null disables media emulation.
      • returns: <Promise>

      Parameters

      • mediaType: "screen" | "print"

      Returns Promise<void>

    • Emulates network conditions (download/upload throughput in bytes per second, latency in milliseconds); null ends the emulation.

      Parameters

      • networkConditions: { download: number; latency: number; offline?: boolean; upload: number }

      Returns Promise<void>

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

      Parameters

      • tz: string

      Returns Promise<void>

      // emulate to Asia/Makassar a.k.a GMT+8
      await page.emulateTimezone('Asia/Makassar');
    • Simulates a vision deficiency on the rendered page.

      Parameters

      • Optionaltype:
            | "none"
            | "achromatopsia"
            | "blurredVision"
            | "deuteranopia"
            | "protanopia"
            | "tritanopia"
            | "reducedContrast"

        "none", "achromatopsia", "blurredVision", "deuteranopia", "protanopia", "tritanopia" or "reducedContrast"

      Returns Promise<void>

      • pageFunction <function|string> Function to be evaluated in the page context
      • ...args <...Serializable|JSHandle> Arguments to pass to pageFunction
      • returns: <Promise<Serializable>> Promise which resolves to the return value of pageFunction

      If the function passed to the page.evaluate returns a Promise, then page.evaluate would wait for the promise to resolve and return its value.

      If the function passed to the page.evaluate returns a non-Serializable value, then page.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.

      Here is an example request JSON that returns true if the body tag exists.

      {
      url: "https://example.com",
      renderType: "automation",
      overseerScript:'await page.waitForNavigation(); var exists = await page.evaluate(()=>{ return document.getElementsByTagName("body").length >0 }); if(exists!=null){page.meta.store.set("key",exists);} ',
      }

      Passing arguments to pageFunction:

      //overseerScript code
      const result = await page.evaluate(x => {
      return Bluebird.Promise.resolve(8 * x);
      }, 7);
      console.log(result); // prints "56"

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

      //overseerScript code
      console.log(await page.evaluate('1 + 2')); // prints "3"
      const x = 10;
      console.log(await page.evaluate(`1 + ${x}`)); // prints "11"

      Arguments must be JSON values or handles: an element of your script's own page passed as an argument arrives as undefined. A handle (Page.$, Page.$$, Page.evaluateHandle) is accepted as an argument; with one and no selectFrame, the call runs in the main frame only.

      Type Parameters

      • T

      Parameters

      • options: FrameExecOptions
      • pageFunction: (...args: any[]) => T | Promise<T>
      • ...args: any[]

      Returns Promise<any>

      • pageFunction <function|string> Function to be evaluated in the page context
      • ...args <...Serializable|JSHandle> Arguments to pass to pageFunction
      • returns: <Promise<Serializable>> Promise which resolves to the return value of pageFunction

      If the function passed to the page.evaluate returns a Promise, then page.evaluate would wait for the promise to resolve and return its value.

      If the function passed to the page.evaluate returns a non-Serializable value, then page.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.

      Here is an example request JSON that returns true if the body tag exists.

      {
      url: "https://example.com",
      renderType: "automation",
      overseerScript:'await page.waitForNavigation(); var exists = await page.evaluate(()=>{ return document.getElementsByTagName("body").length >0 }); if(exists!=null){page.meta.store.set("key",exists);} ',
      }

      Passing arguments to pageFunction:

      //overseerScript code
      const result = await page.evaluate(x => {
      return Bluebird.Promise.resolve(8 * x);
      }, 7);
      console.log(result); // prints "56"

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

      //overseerScript code
      console.log(await page.evaluate('1 + 2')); // prints "3"
      const x = 10;
      console.log(await page.evaluate(`1 + ${x}`)); // prints "11"

      Arguments must be JSON values or handles: an element of your script's own page passed as an argument arrives as undefined. A handle (Page.$, Page.$$, Page.evaluateHandle) is accepted as an argument; with one and no selectFrame, the call runs in the main frame only.

      Type Parameters

      • T

      Parameters

      • pageFunction: (...args: any[]) => T | Promise<T>
      • ...args: any[]

      Returns Promise<any>

    • Runs pageFunction in the main frame and returns its result as a :class (an :class when the result is a DOM element), instead of copying the result as JSON like Page.evaluate.

      const body = await page.evaluateHandle(() => document.body);
      const html = await body.evaluate((b) => b.innerHTML.length);

      Parameters

      • pageFunction: PageFunction

        function (or its source text) run inside the page

      • ...args: any[]

        JSON values or handles passed to pageFunction

      Returns Promise<JSHandle>

      • pageFunction <function|string> Function to be evaluated in browser context
      • ...args <...Serializable> Arguments to pass to pageFunction
      • returns: <Promise>

      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.

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

      overseerScript:'await page.evaluateOnNewDocument(() => {Object.defineProperty(navigator, "language", {get: function() {return ["de-DE","de"];}});Object.defineProperty(navigator, "languages", {get: function() {return ["de-DE", "de"];}});});',
      

      Type Parameters

      • T

      Parameters

      • pageFunction: (...args: any[]) => T | Promise<T>
      • ...args: any[]

      Returns Promise<NewDocumentScriptEvaluation>

    • Adds a function window[name] to the page (every frame, also after navigations). When the page calls it, your function runs in your overseer script and the page receives its result as a promise.

      pjsc differences:

      • The page passes JSON values. A DOM element argument arrives as an :class that is valid for that call only.
      • Your function must return JSON values; returning a handle is refused.
      • Exposed functions are removed when the render ends.
      • print, showDirectoryPicker, showOpenFilePicker and showSaveFilePicker are pjsc's own and cannot be exposed or removed; a name that is already exposed must be removed first with Page.removeExposedFunction.
      await page.exposeFunction("report", (value) => page.meta.log("from page", value));
      await page.evaluate(() => window.report(document.title));

      Parameters

      • name: string

        the window property name

      • fn: ((...args: any[]) => any) | { default: (...args: any[]) => any }

        the function, or { default: function }

      Returns Promise<void>

      • selector <string> A selector of an element to focus. If there are multiple elements satisfying the selector, the first will be focused.
      • returns: <Promise> Promise which resolves when the element matching selector is successfully focused. The promise will be rejected if there is no element matching selector.

      This method fetches an element with selector and focuses it. If there's no element matching selector, the method throws an error.

      Parameters

      Returns Promise<void>

    • All frames of the page as :class objects, the main frame first. Synchronous: the list is kept current as frames attach, detach and navigate.

      Page.mainFrame returns a frame summary ({url, name, guid}); use page.frames()[0] for the main frame's :class object.

      for (const frame of page.frames()) page.meta.log(frame.url());
      

      Returns Frame[]

    • The page's default navigation timeout in milliseconds (Page.setDefaultNavigationTimeout).

      Returns Promise<number>

    • The page's default timeout in milliseconds for waits (Page.setDefaultTimeout).

      Returns Promise<number>

      • options <Object> Navigation parameters which might have the following properties: - timeout <number> Maximum navigation time in milliseconds, defaults to 30 seconds, pass 0 to disable timeout. The default value can be changed by using the page.setDefaultNavigationTimeout(timeout) or page.setDefaultTimeout(timeout) methods. - waitUntil <string|Array<string>> When to consider navigation succeeded, defaults to load. Given an array of event strings, navigation is considered to be successful after all events have been fired. Events can be either: - load - consider navigation to be finished when the load event is fired. - domcontentloaded - consider navigation to be finished when the DOMContentLoaded event is fired. - networkidle0 - consider navigation to be finished when there are no more than 0 network connections for at least 500 ms. - networkidle2 - consider navigation to be finished when there are no more than 2 network connections for at least 500 ms.
      • returns: <Promise<?Response>> Promise which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. If can not go back, resolves to null.

      Navigate to the previous page in history.

      Parameters

      Returns Promise<void>

      • options <Object> Navigation parameters which might have the following properties: - timeout <number> Maximum navigation time in milliseconds, defaults to 30 seconds, pass 0 to disable timeout. The default value can be changed by using the page.setDefaultNavigationTimeout(timeout) or page.setDefaultTimeout(timeout) methods. - waitUntil <string|Array<<string>> When to consider navigation succeeded, defaults to load. Given an array of event strings, navigation is considered to be successful after all events have been fired. Events can be either: - load - consider navigation to be finished when the load event is fired. - domcontentloaded - consider navigation to be finished when the DOMContentLoaded event is fired. - networkidle0 - consider navigation to be finished when there are no more than 0 network connections for at least 500 ms. - networkidle2 - consider navigation to be finished when there are no more than 2 network connections for at least 500 ms.
      • returns: <Promise<?Response>> Promise which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. If can not go forward, resolves to null.

      Navigate to the next page in history.

      Parameters

      Returns Promise<void>

      • url <string> URL to navigate page to. The url should include scheme, e.g. https://.
      • options <Object> Navigation parameters which might have the following properties: - timeout <number> Maximum navigation time in milliseconds, defaults to 30 seconds, pass 0 to disable timeout. The default value can be changed by using the page.setDefaultNavigationTimeout(timeout) or page.setDefaultTimeout(timeout) methods. - waitUntil <string|Array<string>> When to consider navigation succeeded, defaults to load. Given an array of event strings, navigation is considered to be successful after all events have been fired. Events can be either: - load - consider navigation to be finished when the load event is fired. - domcontentloaded - consider navigation to be finished when the DOMContentLoaded event is fired. - networkidle0 - consider navigation to be finished when there are no more than 0 network connections for at least 500 ms. - networkidle2 - consider navigation to be finished when there are no more than 2 network connections for at least 500 ms. - referer <string> Referer header value. If provided it will take preference over the referer header value set by page.setExtraHTTPHeaders().
      • returns: <Promise<?Response>> Promise which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect.

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

      page.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 response.status().

      NOTE page.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.

      Parameters

      Returns Promise<void>

      • selector <string> A selector to search for element to hover. If there are multiple elements satisfying the selector, the first will be hovered.
      • options allows choosing a specific frame (main frame, or a child IFrame). defaults to searching all frames, stopping at the first successful execution.
      • returns: <Promise> Promise which resolves when the element matching selector is successfully hovered. Promise gets rejected if there's no element matching selector.

      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. If there's no element matching selector, the method throws an error.

      Parameters

      Returns Promise<void>

    • Whether the page is closed.

      Returns Promise<boolean>

    • Whether drag interception is enabled (Page.setDragInterception).

      Returns Promise<boolean>

    • Whether JavaScript is enabled on the page (Page.setJavaScriptEnabled).

      Returns Promise<boolean>

    • Whether service workers are bypassed (Page.setBypassServiceWorker).

      Returns Promise<boolean>

    • Creates a :class for selector in the main frame (synchronous; nothing runs until an action is called). A locator waits for its element to be attached, visible, enabled and stable before it acts, and retries until its timeout.

      await page.locator("button.accept").click();
      await page.locator("#search").fill("phantomjscloud");

      Parameters

      • selectorOrFunction: PageFunction

        a CSS selector (puppeteer selector syntax), or a function (or its source text) run in the page whose truthy result the locator waits for

      Returns Locator

      • returns: <Frame> The page's main frame, as a frame summary (types.Frame: {url, name, guid}).

      Page is guaranteed to have a main frame which persists during navigations.

      To act on the main frame (goto, evaluate, $, locator, ...) use its Frame:class object: page.frames()[0].

      Returns Promise<types.Frame>

    • call this to signal the API to NOT complete when it thinks the page is done loading. Instead, it will complete only when you call Page.done

      Returns Promise<void>

    • returns: <Promise<Object>> Object containing metrics as key/value pairs. - Timestamp <number> The timestamp when the metrics sample was taken. - Documents <number> Number of documents in the page. - Frames <number> Number of frames in the page. - JSEventListeners <number> Number of events in the page. - Nodes <number> Number of DOM nodes in the page. - LayoutCount <number> Total number of full or partial page layout. - RecalcStyleCount <number> Total number of page style recalculations. - LayoutDuration <number> Combined durations of all page layouts. - RecalcStyleDuration <number> Combined duration of all page style recalculations. - ScriptDuration <number> Combined duration of JavaScript execution. - TaskDuration <number> Combined duration of all tasks performed by the browser. - JSHeapUsedSize <number> Used JavaScript heap size. - JSHeapTotalSize <number> Total JavaScript heap size.

      NOTE All timestamps are in monotonic time: monotonically increasing time in seconds since an arbitrary point in the past.

      Returns Promise<Metrics>

    • manipulate a html select element.

      • selector <string> A selector to query page for
      • ...values <...string> 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.
      • returns: <Promise<Array{string}>> An array of option values that have been successfully selected.

      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.

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

      Parameters

      • selector: string
      • ...values: string[]

      Returns Promise<string[]>

    • manipulate a html select element.

      • selector <string> A selector to query page for
      • ...values <...string> 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.
      • returns: <Promise<Array{string}>> An array of option values that have been successfully selected.

      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.

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

      Parameters

      Returns Promise<string[]>

    • Toggles bypassing the page's Content-Security-Policy. Takes effect at the next navigation.

      Parameters

      • enabled: boolean

        true bypasses the policy

      Returns Promise<void>

    • Toggles bypassing the page's service workers for its requests.

      Parameters

      • bypass: boolean

        true bypasses service workers

      Returns Promise<void>

    • Toggles the browser cache for the page's requests (enabled by default).

      Parameters

      • Optionalenabled: boolean

        false disables the cache

      Returns Promise<void>

      • html <string> HTML markup to assign to the page.
      • options <Object> Parameters which might have the following properties: - timeout <number> Maximum time in milliseconds for resources to load, defaults to 30 seconds, pass 0 to disable timeout. The default value can be changed by using the page.setDefaultNavigationTimeout(timeout) or page.setDefaultTimeout(timeout) methods. - waitUntil {string|Array{string>> When to consider setting markup succeeded, defaults to load. Given an array of event strings, setting content is considered to be successful after all events have been fired. Events can be either: - load - consider setting content to be finished when the load event is fired. - domcontentloaded - consider setting content to be finished when the DOMContentLoaded event is fired. - networkidle0 - consider setting content to be finished when there are no more than 0 network connections for at least 500 ms. - networkidle2 - consider setting content to be finished when there are no more than 2 network connections for at least 500 ms.
      • returns: <Promise>

      Parameters

      Returns Promise<void>

      • ...cookies <...Object> - name <string> required - value <string> required - url <string> - domain <string> - path <string> - expires <number> Unix time in seconds. - httpOnly <boolean> - secure <boolean> - sameSite <"Strict"|"Lax">
      • returns: <Promise>
      await page.setCookie(cookieObject1, cookieObject2); 
      

      Parameters

      Returns Promise<void>

    • This setting will change the default maximum navigation time for the following methods and related shortcuts:

      • NOTE page.setDefaultNavigationTimeout takes priority over page.setDefaultTimeout

      Parameters

      • timeout: number

      Returns Promise<void>

    • default: 15000 (15 seconds)

      This setting will change the default maximum time for the following methods and related shortcuts:

      • page.goBack([options])

      • page.goForward([options])

      • page.goto(url[, options])

      • page.reload([options])

      • page.setContent(html[, options])

      • page.waitFor(selectorOrFunctionOrTimeout[, options[, ...args]])

      • page.waitForFunction(pageFunction[, options[, ...args]])

      • page.waitForNavigation([options])

      • page.waitForRequest(urlOrPredicate[, options])

      • page.waitForResponse(urlOrPredicate[, options])

      • page.waitForSelector(selector[, options])

      • page.waitForXPath(xpath[, options])

        NOTE page.setDefaultNavigationTimeout takes priority over page.setDefaultTimeout

      Parameters

      • timeout: number

      Returns Promise<void>

    • Enables drag interception: Mouse.drag then returns the drag data instead of the browser starting a native drag, for use with Mouse.dragEnter, Mouse.dragOver and Mouse.drop.

      Parameters

      • enabled: boolean

        true intercepts drags

      Returns Promise<void>

      • headers <Object> An object containing additional HTTP headers to be sent with every request. All header values must be strings.
      • returns: <Promise>

      The extra HTTP headers will be sent with every request the page initiates.

      NOTE page.setExtraHTTPHeaders does not guarantee the order of headers in the outgoing requests.

      Parameters

      • headers: Record<string, string>

      Returns Promise<void>

      • options <Object> - latitude <number> Latitude between -90 and 90. - longitude <number> Longitude between -180 and 180. - accuracy <number> Optional non-negative accuracy value.
      • returns: <Promise>

      Sets the page's geolocation.

      await page.setGeolocation({latitude: 59.95, longitude: 30.31667});
      

      Parameters

      Returns Promise<void>

    • Enables or disables JavaScript on the page. Takes effect at the next navigation.

      Parameters

      • enabled: boolean

        false disables JavaScript

      Returns Promise<void>

      • enabled <boolean> When true, enables offline mode for the page.

      Parameters

      • enabled: boolean

      Returns Promise<void>

    • Sets the user agent string the page sends with its requests and reports as navigator.userAgent.

      • userAgent <string> Specific user agent to use in this page
      • returns: <Promise>

      Parameters

      • userAgent: string

      Returns Promise<void>

      • viewport <Object> - width <number> page width in pixels. required - height <number> page height in pixels. required - deviceScaleFactor <number> Specify device scale factor (can be thought of as dpr). Defaults to 1. - isMobile <boolean> Whether the meta viewport tag is taken into account. Defaults to false. - hasTouch<boolean> Specifies if viewport supports touch events. Defaults to false - isLandscape <boolean> Specifies if viewport is in landscape mode. Defaults to false.
      • returns: <Promise>
      • NOTE in certain cases, setting viewport will reload the page in order to set the isMobile or hasTouch properties.

      In the case of multiple pages in a single browser, each page can have its own viewport size.

      page.setViewport will resize the page. A lot of websites don't expect phones to change size, so you should set the viewport before navigating to the page.

      await page.setViewport({
      width: 640,
      height: 480,
      deviceScaleFactor: 1,
      });
      await page.goto('https://example.com');

      Parameters

      Returns Promise<void>

      • selector <string> A selector to search for element to tap. If there are multiple elements satisfying the selector, the first will be tapped.
      • returns: <Promise>

      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. If there's no element matching selector, the method throws an error.

      Parameters

      Returns Promise<void>

      • returns: <Promise<string>> The page's title.

      Parameters

      • OptionalframeGuid: string

      Returns Promise<string>

      • selector <string> A selector of an element to type into. If there are multiple elements satisfying the selector, the first will be used.
      • text <string> A text to type into a focused element.
      • options <Object>
        • delay <number> Time to wait between key presses in milliseconds. Defaults to 0.
      • returns: <Promise>

      Sends a keydown, keypress/input, and keyup event for each character in the text.

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

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

      Parameters

      • selector: string
      • text: string
      • Optionaloptions: { delay: number } & FrameExecOptions

      Returns Promise<void>

    • returns a promise resolving to the url.

      Parameters

      • OptionalframeGuid: string

      Returns Promise<string>

    • reads the page's current viewport.

      returns: <?Object<

      • width <number> page width in pixels.
      • height <number> page height in pixels.
      • deviceScaleFactor <number> Specify device scale factor (can be though of as dpr). Defaults to 1.
      • isMobile <boolean> Whether the meta viewport tag is taken into account. Defaults to false.
      • hasTouch<boolean> Specifies if viewport supports touch events. Defaults to false
      • isLandscape <boolean> Specifies if viewport is in landscape mode. Defaults to false.

      Returns Promise<Viewport>

    • waits for the given number of ms

      Parameters

      • ms: number

      Returns Promise<void>

    • returns if/when the current page domContentLoaded event is triggered

      Returns Promise<void>

    • Waits for a frame whose url equals urlOrPredicate, or for which the predicate returns true, and returns it. The current frames are checked first, then every frame change.

      const frame = await page.waitForFrame((f) => f.url().includes("checkout"), { timeout: 10000 });
      

      Parameters

      • urlOrPredicate: string | ((frame: Frame) => boolean | Promise<boolean>)

        the exact frame url, or a function (frame) => boolean | Promise<boolean>

      • Optionaloptions: { timeout?: number }

        timeout in milliseconds; defaults to the page's default timeout (30000 unless Page.setDefaultTimeout changed it); 0 waits without limit. signal is not supported.

      Returns Promise<Frame>

      • pageFunction <function|string> Function to be evaluated in browser context
      • options <Object> Optional waiting parameters - polling <string|number< An interval at which the pageFunction is executed, defaults to raf. If polling is a number, then it is treated as an interval in milliseconds at which the function would be executed. If polling is a string, then it can be one of the following values: - raf - to constantly execute pageFunction in requestAnimationFrame callback. This is the tightest polling mode which is suitable to observe styling changes. - mutation - to execute pageFunction on every DOM mutation. - timeout <number> maximum time to wait for in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout. The default value can be changed by using the page.setDefaultTimeout(timeout) method.
      • ...args <...Serializable|JSHandle> Arguments to pass to pageFunction
      • returns: <Promise<JSHandle>> Promise which resolves when the pageFunction returns a truthy value. It resolves to a JSHandle of the truthy value.

      The waitForFunction can be used to observe viewport size change:

      const watchDog = page.waitForFunction('window.innerWidth &lt; 100');
      await page.setViewport({width: 50, height: 50});
      await watchDog;
      await page.done();
      });

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

      const selector = '.foo';
      await page.waitForFunction(selector => !!document.querySelector(selector), {}, selector);

      Parameters

      Returns Promise<types.Frame>

    • returns if/when the current page load event is triggered

      Returns Promise<void>

    • IMPORTANT This function will not complete until a page Navigation occurs. Thus if the page is already loaded, this function will stall until the next page load occurs.
      So if you await a command that performs a navigation (eg: await page.click("input[type=button][value=Login]"); ) then if the next line calls await page.waitForNavigation() it will block until the api call times out. A workaround is to make sure you do not await the command that calls the navigation (the page.click() command).


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

      Parameters

      Returns Promise<types.Frame>

      const [response] = await Promise.all([
      page.waitForNavigation(), // The promise resolves after a navigation ```load``` event has triggered
      page.click('a.my-link'), // Clicking the link will indirectly cause a navigation
      ]);
      await page.waitForNavigation({waitUntil:"domcontentloaded"}), // awaits until the domReady event has triggered.
      

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

    • Waits until the page's network is idle: at most concurrency requests in flight for idleTime milliseconds.

      Like the other main-frame calls, it first waits until pjsc's own navigation to the request url has finished.

      Parameters

      • Optionaloptions: { concurrency?: number; idleTime?: number; timeout?: number }

        idleTime (default 500 ms), timeout (default: the page's default timeout; 0 = no limit), concurrency (default 0)

      Returns Promise<void>

      • urlOrPredicate <string|function> The request url to wait for, or a predicate function. The predicate receives each request as an HTTPRequest object (methods url(), method(), headers(), resourceType(), ...) and returns (or resolves to) true for the request to wait for. A predicate that throws makes the wait fail.
      • options <Object> Optional waiting parameters - timeout <number> Maximum wait time in milliseconds, defaults to 30 seconds, pass 0 to disable the timeout.
      • returns: <Promise<Request>> The matching request, as a request summary (types.Request, a plain object with its response summary when one has arrived), for both forms.
      const req = await page.waitForRequest("https://example.com/api/data");
      const post = await page.waitForRequest((r) => r.method() === "POST" && r.url().includes("/api/"));
      page.meta.log(post.url, post.postData);

      Parameters

      • url: string | ((request: any) => boolean | Promise<boolean>)
      • Optionaloptions: Timeoutable

      Returns Promise<Request>

      • urlOrPredicate <string|function> The response url to wait for, or a predicate function. The predicate receives each response as an HTTPResponse object (methods url(), status(), headers(), request(), ...) and returns (or resolves to) true for the response to wait for. A predicate that throws makes the wait fail.
      • options <Object> Optional waiting parameters - timeout <number> Maximum wait time in milliseconds, defaults to 30 seconds, pass 0 to disable the timeout.
      • returns: <Promise<Response>> The matching response, as a response summary (types.Response, a plain object with its request summary), for both forms. The response body is not included.
      const res = await page.waitForResponse((r) => r.url().endsWith("/api/data") && r.status() === 200);
      page.meta.log(res.status, res.headers["content-type"]);

      Parameters

      • url: string | ((response: any) => boolean | Promise<boolean>)
      • Optionaloptions: Timeoutable

      Returns Promise<Response>

      • selector <string> A selector of an element to wait for
      • options <Object> Optional waiting parameters - visible <boolean> wait for element to be present in DOM and to be visible, i.e. to not have display: none or visibility: hidden CSS properties. Defaults to false. - hidden <boolean> wait for element to not be found in the DOM or to be hidden, i.e. have display: none or visibility: hidden CSS properties. Defaults to false. - timeout <number> maximum time to wait for in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout. The default value can be changed by using the page.setDefaultTimeout(timeout) method.
      • returns: <Promise<?ElementHandle>> Promise which resolves when element specified by selector string is added to DOM. Resolves to null if waiting for hidden: true and selector is not found in DOM.

      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:

      let currentURL;
      page
      .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 page.done();

      Parameters

      Returns Promise<types.Frame>

      • xpath <string> A xpath of an element to wait for
      • options <Object> Optional waiting parameters - visible <boolean> wait for element to be present in DOM and to be visible, i.e. to not have display: none or visibility: hidden CSS properties. Defaults to false. - hidden <boolean> wait for element to not be found in the DOM or to be hidden, i.e. have display: none or visibility: hidden CSS properties. Defaults to false. - timeout <number> maximum time to wait for in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout. The default value can be changed by using the page.setDefaultTimeout(timeout) method.
      • returns: <Promise<?ElementHandle>> Promise which resolves when element specified by xpath string is added to DOM. Resolves to null if waiting for hidden: true and xpath is not found in DOM.

      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.

      This method works across navigations:

      let currentURL;
      page
      .waitForXPath('//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 page.done();

      Parameters

      Returns Promise<types.Frame>

    • This method returns all of the dedicated WebWorkers associated with the page.

      Returns Promise<{ url: string }[]>