Page provides methods to interact with a single tab or extension background page in the browser.

:::note

One Browser instance might have multiple Page instances.

:::

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

import puppeteer from '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 PageEvent enum.

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

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

To unsubscribe from events use the EventEmitter.off method:

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

Hierarchy

  • EventEmitter<PageEvents>
    • Page

Constructors

  • Returns Page

Accessors

  • get accessibility(): Accessibility
  • {@inheritDoc Accessibility}

    Returns Accessibility

  • get coverage(): Coverage
  • {@inheritDoc Coverage}

    Returns Coverage

  • get keyboard(): Keyboard
  • {@inheritDoc Keyboard}

    Returns Keyboard

  • get mouse(): Mouse
  • {@inheritDoc Mouse}

    Returns Mouse

  • get touchscreen(): Touchscreen
  • {@inheritDoc Touchscreen}

    Returns Touchscreen

  • get tracing(): Tracing
  • {@inheritDoc Tracing}

    Returns Tracing

Methods

  • This method returns all elements matching the selector and passes the resulting array as the first argument to the pageFunction.

    Type Parameters

    • Selector extends string
    • Params extends unknown[]
    • Func extends EvaluateFuncWith<NodeFor<Selector>[], Params> = EvaluateFuncWith<NodeFor<Selector>[], Params>

    Parameters

    Returns Promise<Awaited<ReturnType<Func>>>

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

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

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

    await page.$$eval('input', elements => {
    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:

    const allInputValues = await page.$$eval('input', elements =>
    elements.map(e => e.textContent)
    );
  • This method finds the first element within the page that matches the selector and passes the result as the first argument to the pageFunction.

    Type Parameters

    • Selector extends string
    • Params extends unknown[]
    • Func extends EvaluateFuncWith<NodeFor<Selector>, Params> = EvaluateFuncWith<NodeFor<Selector>, Params>

    Parameters

    Returns Promise<Awaited<ReturnType<Func>>>

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

    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.

    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:

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

    // 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
    );
  • Adds a <script> tag into the page with the desired URL or content.

    Parameters

    • options: FrameAddScriptTagOptions

      Options for the script.

    Returns Promise<ElementHandle<HTMLScriptElement>>

    An ElementHandle | element handle to the injected <script> element.

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

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

    Shortcut for Frame.(addStyleTag:2) | page.mainFrame().addStyleTag(options).

    Parameters

    • options: Omit<FrameAddStyleTagOptions, "url">

    Returns Promise<ElementHandle<HTMLStyleElement>>

    An ElementHandle | element handle to the injected <link> or <style> element.

  • Parameters

    • options: FrameAddStyleTagOptions

    Returns Promise<ElementHandle<HTMLLinkElement>>

  • Provide credentials for HTTP authentication.

    :::note

    Request interception will be turned on behind the scenes to implement authentication. This might affect performance.

    :::

    Parameters

    • credentials: null | Credentials

    Returns Promise<void>

    To disable authentication, pass null.

  • Brings page to front (activates tab).

    Returns Promise<void>

  • Get the browser the page belongs to.

    Returns Browser

  • Get the browser context that the page belongs to.

    Returns BrowserContext

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

    Parameters

    • selector: string

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

    • Optionaloptions: Readonly<ClickOptions>

      Object

    Returns Promise<void>

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

    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 Frame.click | page.mainFrame().click(selector[, options]).

  • Parameters

    • Optionaloptions: {
          runBeforeUnload?: boolean;
      }
      • OptionalrunBeforeUnload?: boolean

    Returns Promise<void>

  • The full HTML contents of the page, including the DOCTYPE.

    Returns Promise<string>

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

  • Creates a Chrome Devtools Protocol session attached to the page.

    Returns Promise<CDPSession>

  • Generates a PDF of the page with the print CSS media type.

    Parameters

    • Optionaloptions: PDFOptions

      options for generating the PDF.

    Returns Promise<ReadableStream<Uint8Array>>

    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.

  • Parameters

    • Rest...cookies: DeleteCookiesRequest[]

    Returns Promise<void>

  • Emit an event and call any associated listeners.

    Type Parameters

    • Key extends keyof PageEvents

    Parameters

    • type: Key

      the event you'd like to emit

    • event: EventsWithWildcard<PageEvents>[Key]

    Returns boolean

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

  • Emulates a given device's metrics and user agent.

    To aid emulation, Puppeteer provides a list of known devices that can be via KnownDevices.

    Parameters

    • device: Device

    Returns Promise<void>

    This method is a shortcut for calling two methods: Page.setUserAgent and Page.setViewport.

    This method will resize the page. A lot of websites don't expect phones to change size, so you should emulate before navigating to the page.

    import {KnownDevices} from 'puppeteer';
    const iPhone = KnownDevices['iPhone 15 Pro'];

    (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();
    })();
  • Enables CPU throttling to emulate slow CPUs.

    Parameters

    • factor: null | number

      slowdown factor (1 is no throttle, 2 is 2x slowdown, etc).

    Returns Promise<void>

  • Emulates the idle state. If no arguments set, clears idle state emulation.

    Parameters

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

      Mock idle state. If not set, clears idle overrides

      • isScreenUnlocked: boolean
      • isUserActive: boolean

    Returns Promise<void>

    // set idle emulation
    await page.emulateIdleState({isUserActive: true, isScreenUnlocked: false});

    // do some checks here
    ...

    // clear idle emulation
    await page.emulateIdleState();
  • Parameters

    • Optionalfeatures: MediaFeature[]

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

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

    • Optionaltype: string

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

    Returns Promise<void>

    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
  • This does not affect WebSockets and WebRTC PeerConnections (see https://crbug.com/563644). To set the page offline, you can use Page.setOfflineMode.

    A list of predefined network conditions can be used by importing PredefinedNetworkConditions.

    Parameters

    • networkConditions: null | NetworkConditions

      Passing null disables network condition emulation.

    Returns Promise<void>

    import {PredefinedNetworkConditions} from 'puppeteer';
    const slow3G = PredefinedNetworkConditions['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();
    })();
  • Parameters

    • OptionaltimezoneId: string

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

    Returns Promise<void>

  • Simulates the given vision deficiency on the page.

    Parameters

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

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

    Returns Promise<void>

    import puppeteer from '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();
    })();
  • Evaluates a function in the page's context and returns the result.

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

    Type Parameters

    • Params extends unknown[]
    • Func extends EvaluateFunc<Params> = EvaluateFunc<Params>

    Parameters

    • pageFunction: string | Func

      a function that is run within the page

    • Rest...args: Params

      arguments to be passed to the pageFunction

    Returns Promise<Awaited<ReturnType<Func>>>

    the return value of pageFunction.

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

    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(() => 2);
    

    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();
  • Type Parameters

    • Params extends unknown[]
    • Func extends EvaluateFunc<Params> = EvaluateFunc<Params>

    Parameters

    • pageFunction: string | Func

      a function that is run within the page

    • Rest...args: Params

      arguments to be passed to the pageFunction

    Returns Promise<HandleFor<Awaited<ReturnType<Func>>>>

    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.evaluateHandle 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):

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

    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:

    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>(...);
    
  • 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.

    Type Parameters

    • Params extends unknown[]
    • Func extends ((...args: Params) => unknown) = ((...args: Params) => unknown)

    Parameters

    • pageFunction: string | Func

      Function to be evaluated in browser context

    • Rest...args: Params

      Arguments to pass to pageFunction

    Returns Promise<NewDocumentScriptEvaluation>

    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);
  • 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.

    :::

    Parameters

    • name: string

      Name of the function on the window object

    • pptrFunction: Function | {
          default: Function;
      }

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

    Returns Promise<void>

    An example of adding an md5 function into the page:

    import puppeteer from 'puppeteer';
    import crypto from '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:

    import puppeteer from 'puppeteer';
    import fs from '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
    const content = await window.readfile('/etc/hosts');
    console.log(content);
    });
    await browser.close();
    })();
  • This method fetches an element with selector and focuses it. If there's no element matching selector, the method throws an error.

    Parameters

    • selector: string

      A selector of an element to focus. If there are multiple elements satisfying the selector, the first will be focused.

    Returns Promise<void>

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

    Shortcut for Frame.focus | page.mainFrame().focus(selector).

  • An array of all frames attached to the page.

    Returns Frame[]

  • Maximum time in milliseconds.

    Returns number

  • This method navigate to the previous page in history.

    Parameters

    • Optionaloptions: WaitForOptions

      Navigation parameters

    Returns Promise<null | HTTPResponse>

    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.

  • This method navigate to the next page in history.

    Parameters

    • Optionaloptions: WaitForOptions

      Navigation Parameter

    Returns Promise<null | HTTPResponse>

    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.

  • {@inheritDoc Frame.goto}

    Parameters

    • url: string
    • Optionaloptions: GoToOptions

    Returns Promise<null | HTTPResponse>

  • 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

    • selector: string

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

    Returns Promise<void>

    Promise which resolves when the element matching selector is successfully hovered. Promise gets rejected if there's no element matching selector.

    Shortcut for page.mainFrame().hover(selector).

  • Indicates that the page has been closed.

    Returns boolean

  • true if drag events are being intercepted, false otherwise.

    Returns boolean

    We no longer support intercepting drag payloads. Use the new drag APIs found on ElementHandle to drag (or just use the Page.mouse).

  • true if the page has JavaScript enabled, false otherwise.

    Returns boolean

  • true if the service worker are being bypassed, false otherwise.

    Returns boolean

  • Gets the number of listeners for a given event.

    Parameters

    • type: keyof PageEvents

      the event to get the listener count for

    Returns number

    the number of listeners bound to the given event

  • The page's main frame.

    Returns Frame

  • Object containing metrics as key/value pairs.

    Returns Promise<Metrics>

    • Timestamp : The timestamp when the metrics sample was taken.

    • Documents : Number of documents in the page.

    • Frames : Number of frames in the page.

    • JSEventListeners : Number of events in the page.

    • Nodes : Number of DOM nodes in the page.

    • LayoutCount : Total number of full or partial page layout.

    • RecalcStyleCount : Total number of page style recalculations.

    • LayoutDuration : Combined durations of all page layouts.

    • RecalcStyleDuration : Combined duration of all page style recalculations.

    • ScriptDuration : Combined duration of JavaScript execution.

    • TaskDuration : Combined duration of all tasks performed by the browser.

    • JSHeapUsedSize : Used JavaScript heap size.

    • JSHeapTotalSize : Total JavaScript heap size.

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

  • Remove an event listener from firing.

    Type Parameters

    • Key extends keyof PageEvents

    Parameters

    • type: Key

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

    • Optionalhandler: Handler<EventsWithWildcard<PageEvents>[Key]>

      the function that should be removed.

    Returns this

    this to enable you to chain method calls.

  • Bind an event listener to fire when an event occurs.

    Type Parameters

    • Key extends keyof PageEvents

    Parameters

    • type: Key

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

    • handler: Handler<EventsWithWildcard<PageEvents>[Key]>

      the function to be called when the event occurs.

    Returns this

    this to enable you to chain method calls.

  • Like on but the listener will only be fired once and then it will be removed.

    Type Parameters

    • Key extends keyof PageEvents

    Parameters

    • type: Key

      the event you'd like to listen to

    • handler: Handler<EventsWithWildcard<PageEvents>[Key]>

      the handler function to run when the event occurs

    Returns this

    this to enable you to chain method calls.

  • Generates a PDF of the page with the print CSS media type.

    Parameters

    • Optionaloptions: PDFOptions

      options for generating the PDF.

    Returns Promise<Buffer>

    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.

  • This method iterates the JavaScript heap and finds all objects with the given prototype.

    Type Parameters

    • Prototype

    Parameters

    • prototypeHandle: JSHandle<Prototype>

      a handle to the object prototype.

    Returns Promise<JSHandle<Prototype[]>>

    Promise which resolves to a handle to an array of objects with this prototype.

    // 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();
  • Reloads the page.

    Parameters

    • Optionaloptions: WaitForOptions

      Options to configure waiting behavior.

    Returns Promise<null | HTTPResponse>

    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.

  • Removes all listeners. If given an event argument, it will remove only listeners for that event.

    Parameters

    • Optionaltype: keyof PageEvents

      the event to remove listeners for.

    Returns this

    this to enable you to chain method calls.

  • The method removes a previously added function via $Page.exposeFunction called name from the page's window object.

    Parameters

    • name: string

    Returns Promise<void>

  • Removes script that injected into page by Page.evaluateOnNewDocument.

    Parameters

    • identifier: string

      script identifier

    Returns Promise<void>

  • Experimental

    Captures a screencast of this page.

    Parameters

    • Optionaloptions: Readonly<ScreencastOptions>

      Configures screencast behavior.

    Returns Promise<ScreenRecorder>

    Recording a page:

    import puppeteer from 'puppeteer';

    // Launch a browser
    const browser = await puppeteer.launch();

    // Create a new page
    const page = await browser.newPage();

    // Go to your site.
    await page.goto("https://www.example.com");

    // Start recording.
    const recorder = await page.screencast({path: 'recording.webm'});

    // Do something.

    // Stop recording.
    await recorder.stop();

    browser.close();

    All recordings will be WebM format using the VP9 video codec. The FPS is 30.

    You must have ffmpeg installed on your system.

  • Captures a screenshot of this page.

    Parameters

    • options: Readonly<ScreenshotOptions> & {
          encoding: "base64";
      }

      Configures screenshot behavior.

    Returns Promise<string>

    While a screenshot is being taken in a BrowserContext, the following methods will automatically wait for the screenshot to finish to prevent interference with the screenshot process: BrowserContext.newPage, Browser.newPage, Page.close.

    Calling Page.bringToFront will not wait for existing screenshot operations.

  • Parameters

    • Optionaloptions: Readonly<ScreenshotOptions>

    Returns Promise<Buffer>

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

    Parameters

    • selector: string

      A Selector to query the page for

    • Rest...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<string[]>

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

    Shortcut for Frame.select | page.mainFrame().select()

  • Toggles bypassing page's Content-Security-Policy.

    Parameters

    • enabled: boolean

      sets bypassing of page's Content-Security-Policy.

    Returns Promise<void>

    NOTE: CSP bypassing happens at the moment of CSP initialization rather than evaluation. Usually, this means that page.setBypassCSP should be called before navigating to the domain.

  • Toggles ignoring of service worker for each request.

    Parameters

    • bypass: boolean

      Whether to bypass service worker and load from network.

    Returns Promise<void>

  • Toggles ignoring cache for each request based on the enabled state. By default, caching is enabled.

    Parameters

    • Optionalenabled: boolean

      sets the enabled state of cache

    Returns Promise<void>

    true

  • Set the content of the page.

    Parameters

    • html: string

      HTML markup to assign to the page.

    • Optionaloptions: WaitForOptions

      Parameters that has some properties.

    Returns Promise<void>

  • Parameters

    • Rest...cookies: CookieParam[]

    Returns Promise<void>

    await page.setCookie(cookieObject1, cookieObject2);
    
  • Parameters

    • timeout: number

      Maximum time in milliseconds.

    Returns void

  • Parameters

    • enabled: boolean

      Whether to enable drag interception.

    Returns Promise<void>

    We no longer support intercepting drag payloads. Use the new drag APIs found on ElementHandle to drag (or just use the Page.mouse).

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

    :::tip

    All HTTP header names are lowercased. (HTTP headers are case-insensitive, so this shouldn’t impact your server code.)

    :::

    :::note

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

    :::

    Parameters

    • headers: Record<string, string>

      An object containing additional HTTP headers to be sent with every request. All header values must be strings.

    Returns Promise<void>

  • Sets the page's geolocation.

    Parameters

    • options: GeolocationOptions

    Returns Promise<void>

    Consider using BrowserContext.overridePermissions to grant permissions for the page to read its geolocation.

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

    • enabled: boolean

      Whether or not to enable JavaScript on the page.

    Returns Promise<void>

    NOTE: changing this value won't affect scripts that have already been run. It will take full effect on the next navigation.

  • Sets the network connection to offline.

    It does not change the parameters used in Page.emulateNetworkConditions

    Parameters

    • enabled: boolean

      When true, enables offline mode for the page.

    Returns Promise<void>

  • Activating request interception enables HTTPRequest.abort, HTTPRequest.continue and HTTPRequest.respond methods. This provides the capability to modify network requests that are made by a page.

    Once request interception is enabled, every request will stall unless it's continued, responded or aborted; or completed using the browser cache.

    See the interception guide for more details.

    Parameters

    • value: boolean

      Whether to enable request interception.

    Returns Promise<void>

    An example of a naïve request interceptor that aborts all image requests:

    import puppeteer from 'puppeteer';
    (async () => {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.setRequestInterception(true);
    page.on('request', interceptedRequest => {
    if (
    interceptedRequest.url().endsWith('.png') ||
    interceptedRequest.url().endsWith('.jpg')
    )
    interceptedRequest.abort();
    else interceptedRequest.continue();
    });
    await page.goto('https://example.com');
    await browser.close();
    })();
  • Parameters

    • userAgent: string

      Specific user agent to use in this page

    • OptionaluserAgentMetadata: UserAgentMetadata

    Returns Promise<void>

    Promise which resolves when the user agent is set.

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

    In the case of multiple pages in a single browser, each page can have its own viewport size. Setting the viewport to null resets the viewport to its default value.

    Parameters

    • viewport: null | Viewport

    Returns Promise<void>

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

    NOTE: in certain cases, setting viewport will reload the page in order to set the isMobile or hasTouch properties.

  • 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

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

    Shortcut for Frame.tap | page.mainFrame().tap(selector).

  • A target this page was created from.

    Returns Target

    Use Page.createCDPSession directly.

  • The page's title

    Returns Promise<string>

    Shortcut for Frame.title | page.mainFrame().title().

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

    Parameters

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

    • Optionaloptions: Readonly<KeyboardTypeOptions>

      have property delay which is the Time to wait between key presses in milliseconds. Defaults to 0.

    Returns Promise<void>

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

    Returns string

    Shortcut for Frame.url | page.mainFrame().url().

  • Returns the current page viewport settings without checking the actual page viewport.

    This is either the viewport set with the previous Page.setViewport call or the default viewport set via BrowserConnectOptions.defaultViewport | BrowserConnectOptions.defaultViewport.

    Returns null | Viewport

  • This method is typically coupled with an action that triggers a device request from an api such as WebBluetooth.

    :::caution

    This must be called before the device request is made. It will not return a currently active device prompt.

    :::

    Parameters

    • Optionaloptions: WaitTimeoutOptions

    Returns Promise<DeviceRequestPrompt>

    const [devicePrompt] = Promise.all([
    page.waitForDevicePrompt(),
    page.click('#connect-bluetooth'),
    ]);
    await devicePrompt.select(
    await devicePrompt.waitForDevice(({name}) => name.includes('My Device'))
    );
  • This method is typically coupled with an action that triggers file choosing.

    :::caution

    This must be called before the file chooser is launched. It will not return a currently active file chooser.

    :::

    :::caution

    Interception of file dialogs triggered via DOM APIs such as window.showOpenFilePicker is currently not supported.

    :::

    Parameters

    • Optionaloptions: WaitTimeoutOptions

    Returns Promise<FileChooser>

    In the "headful" browser, this method results in the native file picker dialog not showing up for the user.

    The following example clicks a button that issues a file chooser and then responds with /tmp/myfile.pdf as if a user has selected this file.

    const [fileChooser] = await Promise.all([
    page.waitForFileChooser(),
    page.click('#upload-file-button'),
    // some button that triggers file selection
    ]);
    await fileChooser.accept(['/tmp/myfile.pdf']);
  • Waits for a frame matching the given conditions to appear.

    Parameters

    • urlOrPredicate: string | ((frame: Frame) => Awaitable<boolean>)
    • Optionaloptions: WaitTimeoutOptions

    Returns Promise<Frame>

    const frame = await page.waitForFrame(async frame => {
    return frame.name() === 'Test';
    });
  • Waits for the provided function, pageFunction, to return a truthy value when evaluated in the page's context.

    Type Parameters

    • Params extends unknown[]
    • Func extends EvaluateFunc<Params> = EvaluateFunc<Params>

    Parameters

    • pageFunction: string | Func

      Function to be evaluated in browser context until it returns a truthy value.

    • Optionaloptions: FrameWaitForFunctionOptions

      Options for configuring waiting behavior.

    • Rest...args: Params

    Returns Promise<HandleFor<Awaited<ReturnType<Func>>>>

    Page.waitForFunction can be used to observe a viewport size change:

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

    Arguments can be passed from Node.js to pageFunction:

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

    The provided pageFunction can be asynchronous:

    const username = 'github-username';
    await page.waitForFunction(
    async username => {
    const githubResponse = await fetch(
    `https://api.github.com/users/${username}`
    );
    const githubUser = await githubResponse.json();
    // show the avatar
    const img = document.createElement('img');
    img.src = githubUser.avatar_url;
    // wait 3 seconds
    await new Promise((resolve, reject) => setTimeout(resolve, 3000));
    img.remove();
    },
    {},
    username
    );
  • Waits for the page to navigate to a new URL or to reload. It is useful when you run code that will indirectly cause the page to navigate.

    Parameters

    • Optionaloptions: WaitForOptions

      Navigation parameters which might have the following properties:

    Returns Promise<null | HTTPResponse>

    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.
    • In case of navigation to a different anchor or navigation due to History API usage, the navigation will resolve with null.
    const [response] = await Promise.all([
    page.waitForNavigation(), // The promise resolves after navigation has finished
    page.click('a.my-link'), // Clicking the link will indirectly cause a navigation
    ]);

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

  • Waits for the network to be idle.

    Parameters

    • Optionaloptions: WaitForNetworkIdleOptions

      Options to configure waiting behavior.

    Returns Promise<void>

    A promise which resolves once the network is idle.

  • Parameters

    • urlOrPredicate: string | AwaitablePredicate<HTTPRequest>

      A URL or predicate to wait for

    • Optionaloptions: WaitTimeoutOptions

      Optional waiting parameters

    Returns Promise<HTTPRequest>

    Promise which resolves to the matched request

    const firstRequest = await page.waitForRequest(
    'https://example.com/resource'
    );
    const finalRequest = await page.waitForRequest(
    request => request.url() === 'https://example.com'
    );
    return finalRequest.response()?.ok();

    Optional Waiting Parameters have:

    • timeout: Maximum wait time in milliseconds, defaults to 30 seconds, pass 0 to disable the timeout. The default value can be changed by using the Page.setDefaultTimeout method.
  • Parameters

    • urlOrPredicate: string | AwaitablePredicate<HTTPResponse>

      A URL or predicate to wait for.

    • Optionaloptions: WaitTimeoutOptions

      Optional waiting parameters

    Returns Promise<HTTPResponse>

    Promise which resolves to the matched response.

    const firstResponse = await page.waitForResponse(
    'https://example.com/resource'
    );
    const finalResponse = await page.waitForResponse(
    response =>
    response.url() === 'https://example.com' && response.status() === 200
    );
    const finalResponse = await page.waitForResponse(async response => {
    return (await response.text()).includes('<html>');
    });
    return finalResponse.ok();

    Optional Parameter have:

    • timeout: Maximum wait time in milliseconds, defaults to 30 seconds, pass 0 to disable the timeout. The default value can be changed by using the Page.setDefaultTimeout method.
  • 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.

    Type Parameters

    • Selector extends string

    Parameters

    • selector: Selector

      A selector of an element to wait for

    • Optionaloptions: WaitForSelectorOptions

      Optional waiting parameters

    Returns Promise<null | ElementHandle<NodeFor<Selector>>>

    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.

    This method works across navigations:

    import puppeteer from 'puppeteer';
    (async () => {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    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 browser.close();
    })();

    The optional Parameter in Arguments options are:

    • visible: A 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: 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: 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 method.

  • All of the dedicated WebWorkers associated with the page.

    Returns WebWorker[]

    This does not contain ServiceWorkers