MailSlurp logo

blog

Capturing Screenshots with Puppeteer and Node.js: A Step-by-Step Guide

Capture full-page or viewport screenshots with Puppeteer and Node.js using a practical script you can adapt for automated browser tests and reports.

If you need the same screenshot on every test or build run, Puppeteer is a straightforward choice. Its Node.js API controls Chrome or Chromium through the DevTools Protocol, so you can open a page, wait for it to settle, and capture the exact viewport or full document. The example below starts small and leaves room for the timing, authentication, and naming rules your own workflow needs.

Prerequisites

Before we begin, ensure that you have Node.js installed on your machine. Download it from the official Node.js website.

Now, let's create a new folder for our project and initialize it with npm init. This will create a package.json file to manage our project's dependencies.

Next, we'll install Puppeteer with the following command:

npm install puppeteer

With Puppeteer installed, let's dive into the code example.

How to capture screenshots with Puppeteer and Node.js

import puppeteer from "puppeteer";
import { join } from "path";
const OUT = process.env.OUT;

const websites = [
  {
    name: "mailslurp",
    srcs: [
      {
        name: "landing",
        href: "https://www.mailslurp.com/",
      },
      {
        name: "pricing",
        href: "https://app.mailslurp.com/pricing/",
      },
    ],
  },
];

(async () => {
  const browser = await puppeteer.launch({
    headless: "new",
    defaultViewport: {
      height: 1400,
      width: 1024,
    },
  });
  await Promise.all(
    websites.map(async (website) => {
      console.log(`Process ${website.name}`);
      const page = await browser.newPage();
      for (const src of website.srcs) {
        const to = join(OUT, `${website.name}-${src.name}.png`);
        console.log(`Save ${src.href} to ${to}`);
        await page.goto(src.href, { waitUntil: "networkidle2" });
        await page.screenshot({ path: to });
      }
      await page.close();
    }),
  );

  await browser.close();
})()
  .then(() => {
    console.log("Done");
  })
  .catch((err) => {
    console.error(err);
    process.exit(1);
  });

export default {};

Conclusion

In this blog post, we have demonstrated how to capture screenshots of web pages using Puppeteer and Node.js. This powerful combination allows developers to automate tasks and perform testing efficiently. By following the provided steps, you can easily incorporate screenshot generation into your projects and create a valuable tool for your web development process.