Puppeteer A high level Node API to control Chrome

Posted By : Nisheet Sharma | 31-Dec-2018

Puppeteer is a Node API library which can be used to control Chrome or Chromium. It runs in headless mode by default but you can configure it to use it in a non-headless mode (i.e in an automated browser window) as well. It can be used to perform various operations such as:

1. Load your custom HTML templates and convert them to images or PDF reports.
2. Perform automated testing of Single Page Applications. You can signal keyboard inputs, submit forms etc.
3. Diagnose performance issues in your application.



1. NodeJs v6.4.0 & above.



npm install puppeteer

Please note the above command will download a recent version of chromium as well. If you already have chromium or chrome installed you can just install the puppeteer core package as shown below:

npm install puppeteer-core


Here's a simple example to take a screenshot of a webpage:


const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  page.setViewport({ width: 1920, height: 1080});
  await page.goto('https://some-website.com');
  await page.screenshot({path: 'example-image.png'});

  await browser.close();


Running the above code will create an image file with the name 'example-image.png' in your application directory. The dimensions of the image will be the same as the viewport you set, so in the above case the image will have the dimensions 1920x1080.


Now let's see how to use puppeteer to create a pdf document.


const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.setContent('<html> <h1>Your HTML content!!! </h1> </html>', {waitUntil: 'load'});
  await page.pdf({path: 'example.pdf', format: 'A4'});

  await browser.close();


We can even set some custom HTML content using page.setContent() method provided by the puppeteer API as shown in the above example. This code will create an example.pdf document in your application directory using the provided HTML content and the pdf pages will be in 'A4' format.


That's it, we saw how we can create screenshots, pdf documents rather easily using the puppeteer node API. But the puppeteer API is not limited to just this, it has a lot more powerful features. To explore it you can use the following link: https://github.com/GoogleChrome/puppeteer/blob/v1.11.0/docs/api.md 

About Author

Author Image
Nisheet Sharma

Nisheet is a Full Stack Developer (MEAN). He is familiar with C, C++, Java, Html, Css, JavaScript, MySql, MongoDb, AngularJs, NodeJs, ExpressJs.

Request for Proposal

Name is required

Comment is required

Sending message..