Puppeteer
Puppeteer is one of the most popular libraries that abstract the lower-level DevTools protocol from developers and provides a high-level API that you can use to easily instrument Chrome/Chromium and automate browsing sessions. Puppeteer is used for tasks like creating screenshots, crawling pages, and testing web applications.
Puppeteer typically connects to a local Chrome or Chromium browser using the DevTools port. Refer to the
Puppeteer API documentation on the Puppeteer.connect()
method for more information.
The Workers team forked a version of Puppeteer and patched it to connect to the Workers Browser Rendering API instead. Review the The changes between Workers Puppeteer fork and the Puppeteer core are minimal. After connecting, the developers can then use the full Puppeteer API as they would on a standard setup.
Our version is open sourced and can be found in Cloudflare’s fork of Puppeteer. The npm can be installed from npmjs as @cloudflare/puppeteer:
npm install @cloudflare/puppeteer --save-dev
Use Puppeteer in a Worker
Once the browser binding is configured and the @cloudflare/puppeteer
library is installed, Puppeteer can be used in a Worker:
import puppeteer from "@cloudflare/puppeteer";export default {async fetch(request, env) {const browser = await puppeteer.launch(env.MYBROWSER);const page = await browser.newPage();await page.goto("https://example.com");const metrics = await page.metrics();await browser.close();return Response.json(metrics);},};
import puppeteer from "@cloudflare/puppeteer";interface Env {MYBROWSER: Fetcher;}export default {async fetch(request: Request, env: Env): Promise<Response> {const browser = await puppeteer.launch(env.MYBROWSER);const page = await browser.newPage();await page.goto("https://example.com");const metrics = await page.metrics();await browser.close();return Response.json(metrics);},};
This script
launches the env.MYBROWSER
browser, opens a
new page,
goes to
https://example.com/, gets the page load
metrics,
closes the browser and prints metrics in JSON.
Puppeteer API
The full Puppeteer API can be found in the Cloudflare’s fork of Puppeteer.