Browserless Docs

See something wrong with this page? Let us know

The puppeteer project from Google is robust library for driving Chrome, and is well supported by browserless. Switching over from running puppeteer locally to browserless should be straightforward. Below is a sample from GitHub that we’ll use as a basis:

Screenshot Example

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.goto('https://example.com');
  await page.screenshot({ path: 'example.png' });

  browser.close();
})();

This simple script loads the “example.com” webpage and takes a screenshot locally to example.png. To use browserless for this work, the code change to:

Screenshot Example with browserless

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.connect({
    browserWSEndpoint: 'wss://chrome.browserless.io/?token=YOUR_API_KEY'
  });
  const page = await browser.newPage();
  await page.goto('https://example.com');
  await page.screenshot({ path: 'example.png' });

  browser.close();
})();

Instead of launching Chrome locally to run the script with, we instead provide puppeteer with a remote location to target and control. In general, you can replace puppeteer.launch with puppeteer.connect and the rest of your code remains unchanged.

If you want your script to remain flexible, and still launch Chrome during development, you can conditional-ize how puppeteer connects like so:

Screenshot Example in production with browserless

const puppeteer = require('puppeteer');

(async () => {
  const browser = process.env.NODE_ENV === 'production' ?
    await puppeteer.connect({
        browserWSEndpoint: 'wss://chrome.browserless.io/?token=YOUR_API_KEY'
    }) :
    await puppeteer.launch();
  const page = await browser.newPage();
  await page.goto('https://example.com');
  await page.screenshot({ path: 'example.png' });

  browser.close();
})();

We hope this helps you easily get started with browserless and puppeteer!