Options
All
  • Public
  • Public/Protected
  • All
Menu

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

Properties

accessibility

accessibility: Accessibility = new Accessibility( this._internalState )

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

diagnostics

diagnostics: Diagnostics = new Diagnostics( this._internalState )

helpers to troubleshoot automation issues.

see Diagnostics for more information

keyboard

keyboard: Keyboard = new Keyboard( this._internalState )

automate keyboard presses.

see Keyboard for more information

meta

meta: Meta = new Meta( this._internalState )

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.

example
//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: Mouse = new Mouse( this._internalState )

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

See the Mouse documentation for more details.

example
//perform a mouse click
page.mouse.click(200,11);

render

render: Render = new Render( this._internalState, this )

touchscreen

touchscreen: Touchscreen = new Touchscreen( this._internalState )

automate taps on a touch screen.

See Touchscreen for more information

tracing

tracing: Tracing = new Tracing( this._internalState )

perform performance traces.

Methods

$$eval

  • $$eval<T>(selector: string, pageFunction: function, ...args: any[]): Promise<any>
  • $$eval<T>(options: object & FrameExecOptions, pageFunction: function, ...args: any[]): 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

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

          • elms: Element[]
          • Rest ...args: any[]

          Returns T | Promise<T>

    • Rest ...args: any[]

    Returns Promise<any>

  • Type parameters

    • T

    Parameters

    • options: object & FrameExecOptions
    • pageFunction: function
        • (elms: Element[], ...args: any[]): T | Promise<T>
        • Parameters

          • elms: Element[]
          • Rest ...args: any[]

          Returns T | Promise<T>

    • Rest ...args: any[]

    Returns Promise<any>

$eval

  • $eval<T>(selector: string, pageFunction: function, ...args: any[]): Promise<any>
  • $eval<T>(options: object & FrameExecOptions, pageFunction: function, ...args: any[]): 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: function
        • (elm: Element, ...args: any[]): T | Promise<T>
        • Parameters

          • elm: Element
          • Rest ...args: any[]

          Returns T | Promise<T>

    • Rest ...args: any[]

    Returns Promise<any>

  • Type parameters

    • T

    Parameters

    • options: object & FrameExecOptions
    • pageFunction: function
        • (elm: Element, ...args: any[]): T | Promise<T>
        • Parameters

          • elm: Element
          • Rest ...args: any[]

          Returns T | Promise<T>

    • Rest ...args: any[]

    Returns Promise<any>

addScriptTag

    • 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>

addStyleTag

    • 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>

authenticate

  • authenticate(options: object): Promise<void>
    • credentialOptions <?Object<
    • username <string>
    • password <string>
    • returns: <Promise>

    Provide credentials for HTTP authentication.

    To disable authentication, pass null.

    Parameters

    • options: object

    Returns Promise<void>

bringToFront

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

    Returns Promise<void>

click

    • 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<any>

content

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

    Parameters

    Returns Promise<any>

    a string containing html/plainText.

cookies

  • cookies(...urls: string[]): Promise<Cookie[]>
    • ...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

    • Rest ...urls: string[]

    Returns Promise<Cookie[]>

deleteCookie

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

    Parameters

    Returns Promise<void>

done

  • done(code?: number, reason?: string): 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

    • Default value code: number = 200
    • Default value reason: string = "normal"

    Returns Promise<void>

emulate

    • 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>

emulateMedia

  • emulateMedia(mediaType: "screen" | "print"): Promise<void>
    • 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>

evaluate

  • evaluate<T>(options: FrameExecOptions, pageFunction: function, ...args: any[]): Promise<any>
  • evaluate<T>(pageFunction: function, ...args: any[]): 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.

    Passing arguments to pageFunction:

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

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

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

    ElementHandle instances can be passed as arguments to the page.evaluate:

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

    Type parameters

    • T

    Parameters

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

          • Rest ...args: any[]

          Returns T | Promise<T>

    • Rest ...args: any[]

    Returns Promise<any>

  • Type parameters

    • T

    Parameters

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

          • Rest ...args: any[]

          Returns T | Promise<T>

    • Rest ...args: any[]

    Returns Promise<any>

evaluateOnNewDocument

  • evaluateOnNewDocument<T>(pageFunction: function, ...args: any[]): Promise<void>
    • 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:

    // 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);

    Type parameters

    • T

    Parameters

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

          • Rest ...args: any[]

          Returns T | Promise<T>

    • Rest ...args: any[]

    Returns Promise<void>

focus

    • 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<any>

goBack

    • 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>

goForward

    • 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>

goto

    • 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<any>

hover

    • 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<any>

mainFrame

  • mainFrame(): Promise<Frame>
    • returns: <Frame> The page's main frame.

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

    Returns Promise<Frame>

manualWait

  • manualWait(): Promise<void>
  • 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>

metrics

  • metrics(): Promise<Metrics>
  • 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>

on

  • on(this: Page, eventName: K, handler: PageOnEvents[K]): any
  • 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

    Parameters

    • this: Page
    • eventName: K
    • handler: PageOnEvents[K]

    Returns any

pdf

  • shortcut to [[render.pdf]]

    Parameters

    Returns Promise<void>

reload

  • reloads the page. can pass navigation options.

    Parameters

    Returns Promise<void>

screenshot

  • shortcut to [[render.screenshot]]

    Parameters

    Returns Promise<void>

select

  • select(selector: string, ...values: string[]): Promise<string[]>
  • select(selector: string, options?: FrameExecOptions, ...values: string[]): 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

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

    Returns Promise<string[]>

  • Parameters

    Returns Promise<string[]>

setContent

    • 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<any>

setCookie

  • setCookie(...cookies: SetCookie[]): 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>

setDefaultNavigationTimeout

  • setDefaultNavigationTimeout(timeout: number): 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>

setDefaultTimeout

  • setDefaultTimeout(timeout: number): 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>

setExtraHTTPHeaders

  • setExtraHTTPHeaders(headers: Record<string, string>): 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>

setGeolocation

  • setGeolocation(options: GeoOptions): 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>

setOfflineMode

  • setOfflineMode(enabled: boolean): Promise<void>
    • enabled <boolean> When true, enables offline mode for the page.

    Parameters

    • enabled: boolean

    Returns Promise<void>

setUserAgent

  • setUserAgent(userAgent: string): Promise<void>
  • Parameters

    • userAgent: string

    Returns Promise<void>

setViewport

  • setViewport(viewport: Viewport): 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>

tap

    • 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<any>

title

  • title(frameGuid?: string): Promise<any>
    • returns: <Promise<string>> The page's title.

    Parameters

    • Optional frameGuid: string

    Returns Promise<any>

type

  • type(selector: string, text: string, options?: object & FrameExecOptions): Promise<any>
    • 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

    Returns Promise<any>

url

  • url(frameGuid?: string): Promise<any>
  • returns a promise resolving to the url.

    Parameters

    • Optional frameGuid: string

    Returns Promise<any>

viewport

  • viewport(): Promise<Viewport>
  • 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>

waitForDelay

  • waitForDelay(ms: number): Promise<any>
  • waits for the given number of ms

    Parameters

    • ms: number

    Returns Promise<any>

waitForDomReady

  • waitForDomReady(): Promise<void>
  • returns if/when the current page domContentLoaded event is triggered

    Returns Promise<void>

waitForFunction

    • 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<any>

waitForLoad

  • waitForLoad(): Promise<void>
  • returns if/when the current page load event is triggered

    Returns Promise<void>

waitForNavigation

  • 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:

    example
    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
    ]);
    example
    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.

    Parameters

    Returns Promise<any>

waitForRequest

  • Parameters

    Returns Promise<Request>

waitForResponse

  • Parameters

    Returns Promise<Response>

waitForSelector

    • 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<any>

waitForXPath

    • 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<any>

workers

  • workers(): Promise<object[]>
  • This method returns all of the dedicated WebWorkers associated with the page.

    Returns Promise<object[]>