### Basic Puppeteer Example Source: https://pptr.dev/ Launches a browser, navigates to a page, interacts with elements, and extracts text. Ensure Puppeteer is installed before running. ```javascript import puppeteer from 'puppeteer'; // Or import puppeteer from 'puppeteer-core'; // Launch the browser and open a new blank page. const browser = await puppeteer.launch(); const page = await browser.newPage(); // Navigate the page to a URL. await page.goto('https://developer.chrome.com/'); // Set the screen size. await page.setViewport({width: 1080, height: 1024}); // Open the search menu using the keyboard. await page.keyboard.press('/'); // Type into search box using accessible input name. await page.locator('::-p-aria(Search)').fill('automate beyond recorder'); // Wait and click on first result. await page.locator('.devsite-result-item-link').click(); // Locate the full title with a unique string. const textSelector = await page .locator('::-p-text(Customize and automate)') .waitHandle(); const fullTitle = await textSelector?.evaluate(el => el.textContent); // Print the full title. console.log('The title of this blog post is "%s".', fullTitle); await browser.close(); ``` -------------------------------- ### Use Custom Provider with Puppeteer Install API Source: https://pptr.dev/browsers-api This example demonstrates how to use the custom provider with the Puppeteer install API. It shows instantiating the custom provider and passing it in the 'providers' array to the install function. ```typescript import {install} from '@puppeteer/browsers'; const customProvider = new SimpleMirrorProvider('https://internal.company.com'); await install({ browser: Browser.CHROME, buildId: '120.0.6099.109', platform: BrowserPlatform.LINUX, cacheDir: '/tmp/puppeteer-cache', providers: [customProvider], }); ``` -------------------------------- ### Install Puppeteer with Bun Source: https://pptr.dev/guides/installation Use this command to install the puppeteer package using Bun. ```bash bun add puppeteer ``` -------------------------------- ### Get Help for Specific CLI Commands Source: https://pptr.dev/browsers-api Access detailed help for individual @puppeteer/browsers commands like install, launch, clear, and list. ```bash npx @puppeteer/browsers install --help # help for the install command npx @puppeteer/browsers launch --help # help for the launch command npx @puppeteer/browsers clear --help # help for the clear command npx @puppeteer/browsers list --help # help for the list command ``` -------------------------------- ### install Source: https://pptr.dev/browsers-api Downloads and unpacks the browser archive according to the InstallOptions. ```APIDOC ## install ### Description Downloads and unpacks the browser archive according to the InstallOptions. ### Parameters #### Query Parameters - **options** (object) - Required - Options for the installation process. See InstallOptions interface for details. ``` -------------------------------- ### Install Puppeteer with npm Source: https://pptr.dev/ Installs Puppeteer, which downloads a compatible Chrome version. Use puppeteer-core to install only the library. ```bash npm i puppeteer # Downloads compatible Chrome during installation. npm i puppeteer-core # Alternatively, install as a library, without downloading Chrome. ``` -------------------------------- ### Install Puppeteer with Yarn Source: https://pptr.dev/guides/installation Use this command to install the puppeteer package using Yarn. ```bash yarn add puppeteer ``` -------------------------------- ### install (no unpack) Source: https://pptr.dev/browsers-api Downloads the browser archive according to the InstallOptions without unpacking. ```APIDOC ## install ### Description Downloads the browser archive according to the InstallOptions without unpacking. ### Parameters #### Query Parameters - **options** (object) - Required - Options for the download process. See InstallOptions interface for details. ``` -------------------------------- ### Basic Puppeteer Workflow Source: https://pptr.dev/guides/getting-started This snippet demonstrates a complete workflow: launching a browser, opening a new page, navigating to a URL, setting viewport, performing a search, clicking a result, and extracting text. Ensure Puppeteer is installed (`npm install puppeteer`). ```javascript import puppeteer from 'puppeteer'; // Or import puppeteer from 'puppeteer-core'; // Launch the browser and open a new blank page. const browser = await puppeteer.launch(); const page = await browser.newPage(); // Navigate the page to a URL. await page.goto('https://developer.chrome.com/'); // Set screen size. await page.setViewport({width: 1080, height: 1024}); // Open the search menu using the keyboard. await page.keyboard.press('/'); // Type into search box using accessible input name. await page.locator('::-p-aria(Search)').fill('automate beyond recorder'); // Wait and click on first result. await page.locator('.devsite-result-item-link').click(); // Locate the full title with a unique string. const textSelector = await page .locator('::-p-text(Customize and automate)') .waitHandle(); const fullTitle = await textSelector?.evaluate(el => el.textContent); // Print the full title. console.log('The title of this blog post is "%s".', fullTitle); await browser.close(); ``` -------------------------------- ### Dockerfile for Alpine Linux with Puppeteer Source: https://pptr.dev/troubleshooting A Dockerfile example for Alpine Linux that installs Chromium and Puppeteer, configuring it to use the system's Chromium browser. ```dockerfile FROM alpine # Installs Chromium (100) package. RUN apk add --no-cache \ chromium \ nss \ freetype \ harfbuzz \ ca-certificates \ ttf-freefont \ nodejs \ yarn ... # Tell Puppeteer to skip installing Chrome. We'll be using the installed package. ENV PUPPETEER_EXECUTABLE_PATH=/usr/bin/chromium-browser # Puppeteer v13.5.0 works with Chromium 100. RUN yarn add puppeteer@13.5.0 # Add user so we don't need --no-sandbox. RUN addgroup -S pptruser && adduser -S -G pptruser pptruser \ && mkdir -p /home/pptruser/Downloads /app \ && chown -R pptruser:pptruser /home/pptruser \ && chown -R pptruser:pptruser /app # Run everything after as non-privileged user. USER pptruser ... ``` -------------------------------- ### Install Puppeteer with npm Source: https://pptr.dev/guides/installation Use this command to install the puppeteer package using npm. ```bash npm i puppeteer ``` -------------------------------- ### Install Puppeteer with pnpm Source: https://pptr.dev/guides/installation Use this command to install the puppeteer package using pnpm. ```bash pnpm add puppeteer ``` -------------------------------- ### Install Dependencies for Headless Chrome on GitlabCI Source: https://pptr.dev/troubleshooting Installs necessary system packages in a GitlabCI environment to enable launching headless Chrome. ```bash before_script: - apt-get update - apt-get install -yq gconf-service libasound2 libatk1.0-0 libc6 libcairo2 libcups2 libdbus-1-3 libexpat1 libfontconfig1 libgbm1 libgcc1 libgconf-2-4 libgdk-pixbuf2.0-0 libglib2.0-0 libgtk-3-0 libnspr4 libpango-1.0-0 libpangocairo-1.0-0 libstdc++6 libx11-6 libx11-xcb1 libxcb1 libxcomposite1 libxcursor1 libxdamage1 libxext6 libxfixes3 libxi6 libxrandr2 libxrender1 libxss1 libxtst6 ca-certificates fonts-liberation libnss3 lsb-release xdg-utils wget ``` -------------------------------- ### Install Dependencies Source: https://pptr.dev/contributing Install project dependencies using npm. Optionally, set PUPPETEER_BROWSER to firefox to download Firefox by default. ```bash npm install ``` ```bash PUPPETEER_BROWSER=firefox npm install ``` -------------------------------- ### Synchronous getDownloadUrl Example Source: https://pptr.dev/browsers-api/browsers.browserprovider.getdownloadurl A synchronous implementation of getDownloadUrl for simple URL construction. It maps the platform and constructs the URL directly. ```javascript getDownloadUrl(options) { const platform = mapPlatform(options.platform); return new URL(`https://releases.example.com/v${options.buildId}/${platform}.zip`); } ``` -------------------------------- ### List Installed Browsers with CLI Source: https://pptr.dev/browsers-api Use the 'list' command in the @puppeteer/browsers CLI to view all currently installed browsers. ```bash npx @puppeteer/browsers list ``` -------------------------------- ### Basic E2E Test Structure with Puppeteer Source: https://pptr.dev/guides/ng-schematics This example demonstrates the basic structure for an E2E test using Puppeteer, including setup hooks and interacting with a page. ```typescript // Testing framework specific imports import {setupBrowserHooks, getBrowserState} from './utils'; describe('', function () { setupBrowserHooks(); it('is running', async function () { const {page} = getBrowserState(); // Query elements await page .locator('my-component') // Click on the element once found .click(); }); }); ``` -------------------------------- ### CircleCI Node Image Configuration Source: https://pptr.dev/troubleshooting Example CircleCI configuration snippet to start with a NodeJS image. Set NODE_ENV to development if Puppeteer is in devDependencies. ```yaml docker: - image: circleci/node:14 # Use your desired version environment: NODE_ENV: development # Only needed if puppeteer is in `devDependencies` ``` -------------------------------- ### launch Source: https://pptr.dev/api Launches a new browser instance. This function can be used to start a new browser with specified options. ```APIDOC ## Function launch ### Description Launches a new browser instance. ### Signature launch(options) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response None ### Error Handling None ``` -------------------------------- ### Install Chromium on Amazon Linux Source: https://pptr.dev/troubleshooting Install the Chromium browser using yum after enabling EPEL on Amazon Linux. ```bash sudo yum install -y chromium ``` -------------------------------- ### Install Browsers using @puppeteer/browsers CLI Source: https://pptr.dev/browsers-api Download and install various browser versions and types using the @puppeteer/browsers CLI. Supports stable, canary, specific versions, and milestones. ```bash # Download the latest available Chrome for Testing binary corresponding to the Stable channel. npx @puppeteer/browsers install chrome@stable # Download a specific Chrome for Testing version. npx @puppeteer/browsers install chrome@116.0.5793.0 # Download the latest Chrome for Testing version for the given milestone. npx @puppeteer/browsers install chrome@117 # Download the latest available ChromeDriver version corresponding to the Canary channel. npx @puppeteer/browsers install chromedriver@canary # Download a specific ChromeDriver version. npx @puppeteer/browsers install chromedriver@116.0.5793.0 # On Ubuntu/Debian and only for Chrome, install the browser and required system dependencies. # If the browser version has already been installed, the command # will still attempt to install system dependencies. # Requires root privileges. npx puppeteer browsers install chrome --install-deps ``` -------------------------------- ### Install EPEL on Amazon Linux Source: https://pptr.dev/troubleshooting Enable EPEL repository to install additional packages like Chromium on Amazon Linux. ```bash sudo amazon-linux-extras install epel -y ``` -------------------------------- ### Get Cookies from Browser Context Source: https://pptr.dev/guides/cookies Retrieves all cookies available in the browser's default context. This example first navigates to a page and sets a cookie via script evaluation before logging the cookies. ```javascript import puppeteer from 'puppeteer'; const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto('https://example.com'); // In this example, we set a cookie using script evaluation. // Cookies can be set by the page/server in various ways. await page.evaluate(() => { document.cookie = 'myCookie = MyCookieValue'; }); console.log(await browser.cookies()); // print available cookies. ``` -------------------------------- ### Configure Dual-Screen Setup with Command Line Source: https://pptr.dev/guides/screen-configuration Use the `--screen-info` command-line argument to define multiple screens with specific dimensions, orientations, and labels for headless Chrome. This configures a primary 800x600 landscape screen and a secondary 600x800 portrait screen. ```javascript import puppeteer from 'puppeteer-core'; const browser = await puppeteer.launch({ args: ['--screen-info={800x600 label=1st}{600x800 label=2nd}'], }); const screens = await browser.screens(); const screenInfos = screens.map( s => `Screen [${s.id}]` + ` ${s.left},${s.top} ${s.width}x${s.height}` + ` label='${s.label}'` + ` isPrimary=${s.isPrimary}` + ` isExtended=${s.isExtended}` + ` isInternal=${s.isInternal}` + ` colorDepth=${s.colorDepth}` + ` devicePixelRatio=${s.devicePixelRatio}` + ` avail=${s.availLeft},${s.availTop} ${s.availWidth}x${s.availHeight}` + ` orientation.type=${s.orientation.type}` + ` orientation.angle=${s.orientation.angle}`, ); console.log(`Number of screens: ${screens.length}\n` + screenInfos.join('\n')); await browser.close(); ``` -------------------------------- ### Install Browsers using Bun Source: https://pptr.dev/guides/configuration Use Bun to install browsers supported by Puppeteer. This command downloads the necessary browser binaries for Puppeteer to use. ```bash bun x puppeteer browsers install ``` -------------------------------- ### Install Browsers using npm Source: https://pptr.dev/guides/configuration Use npm to install browsers supported by Puppeteer. This command downloads the necessary browser binaries for Puppeteer to use. ```bash npx puppeteer browsers install ``` -------------------------------- ### Install proxy-agent Package Source: https://pptr.dev/browsers-api Install the 'proxy-agent' package using npm, which is required for the library and CLI to respect HTTP_PROXY, HTTPS_PROXY, and NO_PROXY environment variables. ```bash npm install proxy-agent ``` -------------------------------- ### Asynchronous getDownloadUrl Example with Version Mapping Source: https://pptr.dev/browsers-api/browsers.browserprovider.getdownloadurl An asynchronous implementation of getDownloadUrl that resolves the Electron version before constructing the download URL. Handles cases where the version cannot be resolved. ```javascript async getDownloadUrl(options) { const electronVersion = await resolveElectronVersion(options.buildId); if (!electronVersion) return null; const platform = mapPlatform(options.platform); return new URL(`https://github.com/electron/electron/releases/download/v${electronVersion}/${platform}.zip`); } ``` -------------------------------- ### Launch Browser Instance Source: https://pptr.dev/api/puppeteer.puppeteernode.launch Launches a browser instance using PuppeteerNode. The example shows how to filter out default arguments, specifically '--mute-audio'. ```javascript const browser = await puppeteer.launch({ ignoreDefaultArgs: ['--mute-audio'] }); ``` -------------------------------- ### computeSystemExecutablePath Source: https://pptr.dev/browsers-api Returns a path to a system-wide Chrome installation given a release channel name by checking known installation locations. Throws an error if the Chrome instance is not found at the expected path. ```APIDOC ## computeSystemExecutablePath ### Description Returns a path to a system-wide Chrome installation given a release channel name by checking known installation locations. If Chrome instance is not found at the expected path, an error is thrown. ### Parameters #### Query Parameters - **options** (object) - Required - Options object. - **channel** (string) - Required - The release channel name (e.g., 'stable', 'beta', 'dev', 'canary'). ### Response #### Success Response (200) - **executablePath** (string) - The path to the system-wide Chrome installation. ``` -------------------------------- ### Install Browsers using Yarn Source: https://pptr.dev/guides/configuration Use Yarn to install browsers supported by Puppeteer. This command downloads the necessary browser binaries for Puppeteer to use. ```bash yarn dlx puppeteer browsers install ``` -------------------------------- ### Install Browsers using pnpm Source: https://pptr.dev/guides/configuration Use pnpm to install browsers supported by Puppeteer. This command downloads the necessary browser binaries for Puppeteer to use. ```bash pnpm dlx puppeteer browsers install ``` -------------------------------- ### Install CentOS Dependencies for Chrome Source: https://pptr.dev/troubleshooting List of common dependencies required for Chrome on CentOS-based systems. Ensure these are installed before launching Puppeteer. ```bash alsa-lib.x86_64 atk.x86_64 cups-libs.x86_64 gtk3.x86_64 ipa-gothic-fonts libXcomposite.x86_64 libXcursor.x86_64 libXdamage.x86_64 libXext.x86_64 libXi.x86_64 libXrandr.x86_64 libXScrnSaver.x86_64 libXtst.x86_64 pango.x86_64 xorg-x11-fonts-100dpi xorg-x11-fonts-75dpi xorg-x11-fonts-cyrillic xorg-x11-fonts-misc xorg-x11-fonts-Type1 xorg-x11-utils ``` -------------------------------- ### Load Extension at Runtime Source: https://pptr.dev/guides/chrome-extensions Install a Chrome extension after Puppeteer has launched by using `browser.installExtension()`. This method returns the extension ID. ```javascript import puppeteer from 'puppeteer'; import path from 'path'; const pathToExtension = path.join(process.cwd(), 'my-extension'); const browser = await puppeteer.launch({ pipe: true, enableExtensions: true, }); const extensionId = await browser.installExtension(pathToExtension); ``` -------------------------------- ### Run Sandbox Smoke Tests Source: https://pptr.dev/guides/ng-schematics Execute this command to run smoke tests that create fresh Angular installations, install schematics, and run initial E2E tests. ```bash node tools/smoke.mjs ``` -------------------------------- ### Launch a new browser instance Source: https://pptr.dev/guides/browser-management Launches a new browser instance and opens a new page. This is the most common way to start automating with Puppeteer. ```javascript import puppeteer from 'puppeteer'; const browser = await puppeteer.launch(); const page = await browser.newPage(); // ... ``` -------------------------------- ### Example of using ElementHandle.waitForSelector with page navigation Source: https://pptr.dev/api/puppeteer.elementhandle.waitforselector This example demonstrates how to use ElementHandle.waitForSelector in conjunction with page navigation to log the URL once an image element is found. It iterates through a list of URLs, navigating to each and waiting for an 'img' tag. ```javascript import puppeteer from 'puppeteer'; const browser = await puppeteer.launch(); const page = await browser.newPage(); let currentURL; page .mainFrame() .waitForSelector('img') .then(() => console.log('First URL with image: ' + currentURL)); for (currentURL of [ 'https://example.com', 'https://google.com', 'https://bbc.com', ]) { await page.goto(currentURL); } await browser.close(); ``` -------------------------------- ### Travis CI Configuration Source: https://pptr.dev/troubleshooting Example .travis.yml configuration for running Puppeteer tests. Ensure the xvfb service is launched for non-headless Chrome. ```yaml language: node_js node_js: node services: xvfb script: - npm test ``` -------------------------------- ### getInstalledBrowsers Source: https://pptr.dev/browsers-api Returns metadata about browsers installed in the cache directory. ```APIDOC ## getInstalledBrowsers ### Description Returns metadata about browsers installed in the cache directory. ### Parameters #### Query Parameters - **options** (object) - Optional - Options for filtering installed browsers. ``` -------------------------------- ### Intercepting and Responding with Mock Data Source: https://pptr.dev/guides/request-interception This example shows how to intercept a request and respond with custom mock data instead of fetching from the network. Useful for testing. ```javascript await page.setRequestInterception(true); page.on('request', async (request) => { if (request.url() === 'https://api.example.com/data') { await request.respond({ status: 200, contentType: 'application/json', body: JSON.stringify([{ id: 1, name: 'mock data' }]) }); } else { request.continue(); } }); ``` -------------------------------- ### InstalledBrowser.readMetadata() Source: https://pptr.dev/browsers-api/browsers.installedbrowser.readmetadata The `readMetadata()` method is used to retrieve metadata about an installed browser. It returns an object of type `Metadata`. ```APIDOC ## InstalledBrowser.readMetadata() ### Description Reads the metadata of an installed browser. ### Method ``` readMetadata(): Metadata ``` ### Returns Metadata - An object containing the browser's metadata. ``` -------------------------------- ### Run E2E Tests with Puppeteer Schematic Source: https://pptr.dev/guides/ng-schematics After installing the schematics, use this command to execute your end-to-end tests. ```bash ng e2e ``` -------------------------------- ### Zooming into an Element with Mouse.wheel() Source: https://pptr.dev/api/puppeteer.mouse.wheel Example demonstrating how to zoom into an element using the page.mouse.wheel() method. This involves navigating to a page, locating an element, moving the mouse to its center, and then simulating a wheel event. ```javascript await page.goto( 'https://mdn.mozillademos.org/en-US/docs/Web/API/Element/wheel_event$samples/Scaling_an_element_via_the_wheel?revision=1587366', ); const elem = await page.$('div'); const boundingBox = await elem.boundingBox(); await page.mouse.move( boundingBox.x + boundingBox.width / 2, boundingBox.y + boundingBox.height / 2, ); await page.mouse.wheel({deltaY: -100}); ``` -------------------------------- ### Fast Puppeteer Launch on Cloud Run (Express) Source: https://pptr.dev/troubleshooting This example shows the correct way to launch Puppeteer before sending the HTTP response to avoid slow performance on Google Cloud Run. Ensure CPU is always enabled for background tasks. ```javascript app.post('/test-puppeteer', (req, res) => { puppeteer.launch().then(browser => { // A second later... res.json({ jobId: 123, acknowledged: true, }); }); }); ``` -------------------------------- ### BrowserLauncher.launch() Source: https://pptr.dev/api/puppeteer.browserlauncher.launch Launches a new browser instance. Accepts an optional `LaunchOptions` object to configure the browser. ```APIDOC ## BrowserLauncher.launch() ### Description Launches a new browser instance. Accepts an optional `LaunchOptions` object to configure the browser. ### Method launch ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **options** (LaunchOptions) - Optional - Used to configure the browser launch. ### Request Example ```javascript // Example usage (assuming BrowserLauncher is instantiated) const browser = await browserLauncher.launch({ headless: true }); ``` ### Response #### Success Response (Promise) Returns a Promise that resolves to a `Browser` object representing the launched browser instance. #### Response Example ```javascript // Example response structure (conceptual) { // Browser object properties and methods } ``` ``` -------------------------------- ### Install Puppeteer Angular Schematic Source: https://pptr.dev/guides/ng-schematics Run this command in an Angular CLI app directory to add the schematic as a project dependency and follow the prompts. ```bash ng add @puppeteer/ng-schematics ``` -------------------------------- ### Touchscreen.touchStart() Source: https://pptr.dev/api/puppeteer.touchscreen.touchstart Dispatches a `touchstart` event to simulate the beginning of a touch interaction on the screen. It takes the horizontal and vertical coordinates of the touch point as input and returns a handle for the initiated touch. ```APIDOC ## Touchscreen.touchStart() ### Description Dispatches a `touchstart` event to simulate the beginning of a touch interaction. ### Method `touchStart(x: number, y: number): Promise` ### Parameters #### Path Parameters - **x** (number) - Required - Horizontal position of the tap. - **y** (number) - Required - Vertical position of the tap. ### Returns Promise A handle for the touch that was started. ### Example ```javascript // Example usage (conceptual) const touchHandle = await page.touchscreen.touchStart(100, 200); ``` ``` -------------------------------- ### Dockerfile for Running Puppeteer Source: https://pptr.dev/troubleshooting A Dockerfile to set up an environment for running Puppeteer. It installs necessary dependencies, Chrome for Testing, and configures a user. ```dockerfile FROM node:14-slim # Install latest chrome dev package and fonts to support major charsets (Chinese, Japanese, Arabic, Hebrew, Thai and a few others) # Note: this installs the necessary libs to make the bundled version of Chrome for Testing that Puppeteer # installs, work. RUN apt-get update \ && apt-get install -y wget gnupg \ && wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - \ && sh -c 'echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list' \ && apt-get update \ && apt-get install -y google-chrome-stable fonts-ipafont-gothic fonts-wqy-zenhei fonts-thai-tlwg fonts-kacst fonts-freefont-ttf libxss1 \ --no-install-recommends \ && rm -rf /var/lib/apt/lists/* # If running Docker >= 1.13.0 use docker run's --init arg to reap zombie processes, otherwise # uncomment the following lines to have `dumb-init` as PID 1 # ADD https://github.com/Yelp/dumb-init/releases/download/v1.2.2/dumb-init_1.2.2_x86_64 /usr/local/bin/dumb-init # RUN chmod +x /usr/local/bin/dumb-init # ENTRYPOINT ["dumb-init", "--"] # Uncomment to skip the Chrome for Testing download when installing puppeteer. If you do, # you'll need to launch puppeteer with: # browser.launch({executablePath: 'google-chrome-stable'}) # ENV PUPPETEER_SKIP_DOWNLOAD true # Install puppeteer so it's available in the container. RUN npm init -y && \ npm i puppeteer \ # Add user so we don't need --no-sandbox. # same layer as npm install to keep re-chowned files from using up several hundred MBs more space && groupadd -r pptruser && useradd -r -g pptruser -G audio,video pptruser \ && mkdir -p /home/pptruser/Downloads \ && chown -R pptruser:pptruser /home/pptruser \ && chown -R pptruser:pptruser /node_modules \ && chown -R pptruser:pptruser /package.json \ && chown -R pptruser:pptruser /package-lock.json ``` -------------------------------- ### Generate PDF from a Web Page Source: https://pptr.dev/guides/pdf-generation Launches a browser, navigates to a URL, and saves the page as a PDF. Ensure Puppeteer is installed and imported. ```javascript const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto('https://news.ycombinator.com', { waitUntil: 'networkidle2', }); // Saves the PDF to hn.pdf. await page.pdf({ path: 'hn.pdf', }); await browser.close(); ``` -------------------------------- ### Coverage.startJSCoverage() Source: https://pptr.dev/api/puppeteer.coverage.startjscoverage Starts JavaScript coverage for the page. It accepts an optional `options` object to configure coverage behavior. By default, coverage is reset on navigation, anonymous scripts are not reported, raw script coverage is not included, and block coverage is used. ```APIDOC ## startJSCoverage() API ### Description Starts JavaScript coverage for the page. This method allows you to track the execution of JavaScript code. ### Method `startJSCoverage(options?: JSCoverageOptions): Promise` ### Parameters #### Options - **options** (JSCoverageOptions) - Optional - Set of configurable options for coverage. Defaults to `resetOnNavigation : true, reportAnonymousScripts : false, includeRawScriptCoverage : false, useBlockCoverage : true`. ### Returns - **Promise** - Promise that resolves when coverage is started. ### Remarks Anonymous scripts are those without an associated URL, dynamically created using `eval` or `new Function`. If `reportAnonymousScripts` is true, their URLs will start with `debugger://VM` unless a `//# sourceURL` comment is present. ``` -------------------------------- ### Rollup Configuration for Browser Build Source: https://pptr.dev/guides/running-puppeteer-in-the-browser Example Rollup configuration for building a browser-compatible JavaScript bundle with Puppeteer. It specifies the input and output formats, external dependencies, and node resolution settings for a browser environment. ```javascript import {nodeResolve} from '@rollup/plugin-node-resolve'; export default { input: 'main.mjs', output: { format: 'esm', dir: 'out', }, // If you do not need to use WebDriver BiDi protocol, // exclude chromium-bidi/lib/bidiMapper/BidiMapper.js to minimize the bundle size. external: ['chromium-bidi/lib/bidiMapper/BidiMapper.js'], plugins: [ nodeResolve({ // Indicate that we target a browser environment. browser: true, // Exclude any dependencies except for puppeteer-core. // `npm install puppeteer-core` # To install puppeteer-core if needed. resolveOnly: ['puppeteer-core'], }), ], }; ``` -------------------------------- ### Touchscreen.touchStart() Signature Source: https://pptr.dev/api/puppeteer.touchscreen.touchstart This snippet shows the abstract signature of the touchStart method within the Touchscreen class. It indicates the method's parameters and return type. ```typescript class Touchscreen { abstract touchStart(x: number, y: number): Promise; } ``` -------------------------------- ### Launching a Browser and Navigating Source: https://pptr.dev/api Demonstrates how to launch a Puppeteer browser instance, open a new page, navigate to a URL, and interact with an element. ```javascript import puppeteer from 'puppeteer'; const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto('https://example.com'); const hrefElement = await page.$('a'); await hrefElement.click(); // ... ``` -------------------------------- ### Start JavaScript Coverage Source: https://pptr.dev/api/puppeteer.coverage.startjscoverage Initiates JavaScript coverage collection. Optional parameters can be provided to configure coverage behavior, such as reporting anonymous scripts or using block coverage. Defaults are applied if no options are specified. ```typescript class Coverage { startJSCoverage(options?: JSCoverageOptions): Promise; } ``` -------------------------------- ### launch Source: https://pptr.dev/browsers-api Launches a browser process according to LaunchOptions. ```APIDOC ## launch ### Description Launches a browser process according to LaunchOptions. ### Parameters #### Query Parameters - **opts** (object) - Required - Options for launching the browser. See LaunchOptions interface for details. ``` -------------------------------- ### Run Unit Tests with Bun Source: https://pptr.dev/guides/ng-schematics Execute the schematic's unit test suite using Bun. ```bash bun run test ``` -------------------------------- ### Clear Installed Browsers with CLI Source: https://pptr.dev/browsers-api Use the 'clear' command in the @puppeteer/browsers CLI to remove all installed browsers. ```bash npx @puppeteer/browsers clear ``` -------------------------------- ### Run Unit Tests with npm Source: https://pptr.dev/guides/ng-schematics Execute the schematic's unit test suite using npm. ```bash npm run test ``` -------------------------------- ### Conventional Commits Example Source: https://pptr.dev/contributing Example of a commit message following the Conventional Commits format, including a breaking change. ```git fix(page): fix page.pizza method This patch fixes page.pizza so that it works with iframes. Issues: #123, #234 BREAKING CHANGE: page.pizza now delivers pizza at home by default. To deliver to a different location, use the "deliver" option: `page.pizza({deliver: 'work'})`. ``` -------------------------------- ### Install Debian Dependencies for Chrome Source: https://pptr.dev/troubleshooting List of common dependencies required for Chrome on Debian-based systems like Ubuntu. Ensure these are installed before launching Puppeteer. ```bash ca-certificates fonts-liberation libasound2 libatk-bridge2.0-0 libatk1.0-0 c6 cairo2 cups2 libdbus-1-3 libexpat1 libfontconfig1 libgbm1 libgcc1 libglib2.0-0 libgtk-3-0 libnspr4 libnss3 lpango-1.0-0 lpangocairo-1.0-0 libstdc++6 libx11-6 libx11-xcb1 libxcb1 libxcomposite1 libxcursor1 libxdamage1 libxext6 libxfixes3 libxi6 libxrandr2 libxrender1 libxss1 libxtst6 lsb-release wget xdg-utils ``` -------------------------------- ### Run Unit Tests with pnpm Source: https://pptr.dev/guides/ng-schematics Execute the schematic's unit test suite using pnpm. ```bash pnpm run test ``` -------------------------------- ### Build All Packages Source: https://pptr.dev/contributing Build all packages in the Puppeteer project. ```bash npm run build ``` -------------------------------- ### PuppeteerNode.launch() Source: https://pptr.dev/api/puppeteer.puppeteernode.launch Launches a browser instance with given arguments and options when specified. When using with `puppeteer-core`, options.executablePath or options.channel must be provided. ```APIDOC ## PuppeteerNode.launch() ### Description Launches a browser instance with given arguments and options. This method is part of the PuppeteerNode class. ### Method launch ### Parameters #### Options - **options** (LaunchOptions) - Optional - Options to configure launching behavior. ### Returns Promise ### Remarks Puppeteer works best with the version of Chrome for Testing downloaded by default. Using other versions of Chrome may lead to unexpected behavior. For preferred Chrome control, consider Chrome Canary or Dev Channel builds. Refer to provided articles for differences between Chromium and Chrome, and specifics for Linux users. ### Example ```javascript const browser = await puppeteer.launch({ ignoreDefaultArgs: ['--mute-audio'], }); ``` ``` -------------------------------- ### Start D-Bus Service Source: https://pptr.dev/guides/docker Starts the D-Bus service, which is often required by Chrome even in headless mode, though typically not needed for Puppeteer's headless operation. ```bash sudo service dbus start ``` -------------------------------- ### JSCoverage.start() Source: https://pptr.dev/api/puppeteer.jscoverage.start Initiates JavaScript coverage tracking. This method can be configured with options to control how coverage is reset and reported. ```APIDOC ## JSCoverage.start() ### Description Initiates JavaScript coverage tracking. This method can be configured with options to control how coverage is reset and reported. ### Method ```javascript JSCoverage.start(options?: { resetOnNavigation?: boolean; reportAnonymousScripts?: boolean; includeRawScriptCoverage?: boolean; useBlockCoverage?: boolean; }): Promise; ``` ### Parameters #### options - **resetOnNavigation** (boolean) - Optional - If true, coverage will be reset upon navigation. - **reportAnonymousScripts** (boolean) - Optional - If true, anonymous scripts will be included in the coverage report. - **includeRawScriptCoverage** (boolean) - Optional - If true, raw script coverage will be included. - **useBlockCoverage** (boolean) - Optional - If true, block coverage will be used. ### Returns - **Promise** - A promise that resolves when coverage tracking has started. ``` -------------------------------- ### BrowserLauncher Class Source: https://pptr.dev/api Describes a launcher class capable of creating and launching browser instances. ```APIDOC ## Class: BrowserLauncher ### Description Describes a launcher - a class that is able to create and launch a browser instance. **Remarks:** The constructor for this class is marked as internal. Third-party code should not call the constructor directly or create subclasses that extend the `BrowserLauncher` class. ``` -------------------------------- ### Run Unit Tests with Yarn Source: https://pptr.dev/guides/ng-schematics Execute the schematic's unit test suite using Yarn. ```bash yarn run test ``` -------------------------------- ### DefaultProvider.getExecutablePath() Source: https://pptr.dev/browsers-api/browsers.defaultprovider.getexecutablepath Gets the executable path for a browser. This method is part of the DefaultProvider class. ```APIDOC ## DefaultProvider.getExecutablePath() ### Description Retrieves the executable path for a given browser, build ID, and platform. ### Method Signature ```typescript getExecutablePath(options: { browser: Browser; buildId: string; platform: BrowserPlatform; }): string; ``` ### Parameters #### Options - **options** ({ browser: Browser; buildId: string; platform: BrowserPlatform; }) - Required - An object containing the browser, build ID, and platform. - **browser** (Browser) - Required - The browser to get the executable path for. - **buildId** (string) - Required - The build ID of the browser. - **platform** (BrowserPlatform) - Required - The platform for which to get the executable path. ### Returns - **string** - The executable path of the browser. ``` -------------------------------- ### WebMCP.tools() Source: https://pptr.dev/api/puppeteer.webmcp.tools Gets all WebMCP tools defined by the page. This method returns an array of WebMCPTool objects. ```APIDOC ## WebMCP.tools() ### Description Gets all WebMCP tools defined by the page. ### Signature ```typescript class WebMCP { tools(): WebMCPTool[]; } ``` ### Returns WebMCPTool[] - An array of WebMCPTool objects. ``` -------------------------------- ### BrowserLauncher.launch() Signature Source: https://pptr.dev/api/puppeteer.browserlauncher.launch Shows the TypeScript signature for the launch method within the BrowserLauncher class. It accepts optional launch options and returns a Promise resolving to a Browser instance. ```typescript class BrowserLauncher { launch(options?: LaunchOptions): Promise; } ``` -------------------------------- ### Get CDPSession ID Source: https://pptr.dev/api/puppeteer.cdpsession.id The `id()` method returns the unique identifier for the CDPSession. This is a string value. ```typescript class CDPSession { abstract id(): string; } ``` -------------------------------- ### Run Node.js Server with Inspector Source: https://pptr.dev/guides/debugging Execute your Node.js script with the `--inspect-brk` flag to enable debugging. Connect to the inspector in Chrome via `chrome://inspect/#devices`. ```bash node --inspect-brk path/to/script.js ``` -------------------------------- ### Sending a Character Source: https://pptr.dev/api/puppeteer.keyboard.sendcharacter Example of using Keyboard.sendCharacter() to input a character into the page. Modifier keys do not affect this method. ```javascript page.keyboard.sendCharacter('嗨'); ``` -------------------------------- ### JSCoverage.start() Method Signature Source: https://pptr.dev/api/puppeteer.jscoverage.start This snippet shows the signature of the JSCoverage.start() method, including its optional parameters and return type. Use this method to initiate JavaScript coverage collection. ```typescript class JSCoverage { start(options?: { resetOnNavigation?: boolean; reportAnonymousScripts?: boolean; includeRawScriptCoverage?: boolean; useBlockCoverage?: boolean; }): Promise; } ``` -------------------------------- ### Legacy Network Interception Handler Source: https://pptr.dev/guides/network-interception An example of a legacy network interception handler that aborts PNG and JPG requests. ```javascript page.on('request', interceptedRequest => { if (request.isInterceptResolutionHandled()) return; if ( interceptedRequest.url().endsWith('.png') || interceptedRequest.url().endsWith('.jpg') ) interceptedRequest.abort(); else interceptedRequest.continue(); }); ``` -------------------------------- ### Get HTTPResponse from HTTPRequest Source: https://pptr.dev/api/puppeteer.httprequest.response Retrieve the HTTPResponse object for a given HTTPRequest. Returns null if the response has not yet been received. ```typescript class HTTPRequest { abstract response(): HTTPResponse | null; } ``` -------------------------------- ### Recommended Handler with `setInterceptResolutionConfig` Source: https://pptr.dev/guides/request-interception This recommended approach exports a `setInterceptResolutionConfig` function, allowing users to activate Cooperative Intercept Mode and optionally specify custom priorities for handlers. ```javascript // Defaults to undefined which preserves Legacy Mode behavior let _priority = undefined; // Export a module configuration function export const setInterceptResolutionConfig = (priority = 0) => (_priority = priority); /** * Note that this handler uses `DEFAULT_INTERCEPT_RESOLUTION_PRIORITY` to "pass" on this request. It is important to use * the default priority when your handler has no opinion on the request and the intent is to continue() by default. */ page.on('request', interceptedRequest => { if (request.isInterceptResolutionHandled()) return; if ( interceptedRequest.url().endsWith('.png') || interceptedRequest.url().endsWith('.jpg') ) interceptedRequest.abort('failed', _priority); else interceptedRequest.continue( interceptedRequest.continueRequestOverrides(), DEFAULT_INTERCEPT_RESOLUTION_PRIORITY, // Unopinionated continuation ); }); ``` -------------------------------- ### Specify @puppeteer/browsers Version with npx Source: https://pptr.dev/browsers-api Control the version of @puppeteer/browsers used with npx. You can install the latest version or a specific version. ```bash # Always install and use the latest version from the registry. npx @puppeteer/browsers@latest --help # Always use a specifc version. npx @puppeteer/browsers@2.4.1 --help # Always install the latest version and automatically confirm the installation. npx --yes @puppeteer/browsers@latest --help ``` -------------------------------- ### Get Page Workers Source: https://pptr.dev/api/puppeteer.page.workers This snippet shows the signature of the Page.workers() method, which returns an array of WebWorker objects. It does not contain ServiceWorkers. ```typescript class Page { abstract workers(): WebWorker[]; } ``` -------------------------------- ### Get Dialog Message Source: https://pptr.dev/api/puppeteer.dialog.message Retrieves the message string displayed within a dialog box. This method is part of the Dialog class. ```typescript class Dialog { message(): string; } ``` -------------------------------- ### Implement a Custom Browser Provider Source: https://pptr.dev/browsers-api This snippet shows how to implement the BrowserProvider interface to create a custom provider for downloading Chrome from a specified mirror URL. It defines how to check support, construct the download URL, and determine the executable path for different platforms. ```typescript import { BrowserProvider, DownloadOptions, Browser, BrowserPlatform, } from '@puppeteer/browsers'; class SimpleMirrorProvider implements BrowserProvider { constructor(private mirrorUrl: string) {} supports(options: DownloadOptions): boolean { return options.browser === Browser.CHROME; } getDownloadUrl(options: DownloadOptions): URL | null { const {buildId, platform} = options; const filenameMap = { [BrowserPlatform.LINUX]: 'chrome-linux64.zip', [BrowserPlatform.MAC]: 'chrome-mac-x64.zip', [BrowserPlatform.MAC_ARM]: 'chrome-mac-arm64.zip', [BrowserPlatform.WIN32]: 'chrome-win32.zip', [BrowserPlatform.WIN64]: 'chrome-win64.zip', }; const filename = filenameMap[platform]; if (!filename) return null; return new URL(`${this.mirrorUrl}/chrome/${buildId}/${filename}`); } getExecutablePath(options: DownloadOptions): string { const {platform} = options; if ( platform === BrowserPlatform.MAC || platform === BrowserPlatform.MAC_ARM ) { return 'chrome-mac/Chromium.app/Contents/MacOS/Chromium'; } else if (platform === BrowserPlatform.LINUX) { return 'chrome-linux64/chrome'; } else if (platform.includes('win')) { return 'chrome-win64/chrome.exe'; } throw new Error(`Unsupported platform: ${platform}`); } } ``` -------------------------------- ### Discover and Listen for WebMCP Tools Source: https://pptr.dev/guides/webmcp Retrieve a list of currently registered WebMCP tools and set up listeners for `toolsadded` and `toolsremoved` events to react to dynamic changes in tool availability. ```javascript // Get currently registered tools const tools = page.webmcp.tools(); for (const tool of tools) { console.log(`Tool found: ${tool.name} - ${tool.description}`); } // Listen for new tools page.webmcp.on('toolsadded', event => { for (const tool of event.tools) { console.log(`New tool added: ${tool.name}`); } }); // Listen for removed tools page.webmcp.on('toolsremoved', event => { for (const tool of event.tools) { console.log(`Tool removed: ${tool.name}`); } }); ``` -------------------------------- ### Get WebWorker URL Source: https://pptr.dev/api/puppeteer.webworker.url Use the url() method on a WebWorker instance to retrieve its URL. This method returns a string representing the URL. ```typescript class WebWorker { url(): string; } ``` -------------------------------- ### Get Certificate Expiration Timestamp Source: https://pptr.dev/api/puppeteer.securitydetails.validto Retrieves the Unix timestamp indicating when the security certificate expires. This method is part of the SecurityDetails class. ```typescript class SecurityDetails { validTo(): number; } ``` -------------------------------- ### Run @puppeteer/browsers CLI Help Source: https://pptr.dev/browsers-api Use npx to run the @puppeteer/browsers package. This command displays help for all available commands. ```bash npx @puppeteer/browsers --help ``` -------------------------------- ### Upload a File Source: https://pptr.dev/guides/files Use `ElementHandle.uploadFile` to upload a local file. Ensure the file input element is correctly selected. ```javascript const fileElement = await page.waitForSelector('input[type=file]'); await fileElement.uploadFile(['./path-to-local-file']); ``` -------------------------------- ### Load Extension via Launch Options Source: https://pptr.dev/guides/chrome-extensions Load a Chrome extension when launching Puppeteer by specifying its path in `LaunchOptions`. Ensure the extension path is correctly resolved. ```javascript import puppeteer from 'puppeteer'; import path from 'path'; const pathToExtension = path.join(process.cwd(), 'my-extension'); const browser = await puppeteer.launch({ pipe: true, enableExtensions: [pathToExtension], }); ``` -------------------------------- ### Use XPath selectors Source: https://pptr.dev/guides/locators Puppeteer supports XPath selectors prefixed with `-p-xpath`. This example demonstrates waiting for an element using an XPath expression. ```javascript // Runs the `//h2` as the XPath expression. const element = await page.waitForSelector('::-p-xpath(//h2)'); ``` -------------------------------- ### Format Code with Prettier Source: https://pptr.dev/contributing Automatically fix code style issues according to Prettier configuration. ```bash npm run format ``` -------------------------------- ### Stopping a Trace Source: https://pptr.dev/api/puppeteer.tracing.stop Call the stop() method on a Tracing instance to end the trace and retrieve the trace data. Ensure a trace was previously started. ```typescript class Tracing { stop(): Promise; } ```