How to Take a Screenshot of a WebPage with JavaScript

H

In this post, we will learn How to Take a Screenshot of a WebPage with JavaScript. Automatically creating a screenshot of a webpage used to be hard. Using puppeteer it became quite simple. Puppeteer is a headless Chrome Node.js API. So you can programmatically do everything you can do everything with it programmatically, that you manually can do with the Chrome browser.

Take a Screenshot of a WebPage with JavaScript:

So let’s create a screenshot of my blog over at Hivalidity.

First, we’ll have to install puppeteer of course. Run

npm i puppeteer

to install puppeteer.

const puppeteer = require("puppeteer");

// we're using async/await - so we need an async function, that we can run
const run = async () => {
  // open the browser and prepare a page
  const browser = await puppeteer.launch()
  const page = await browser.newPage()

  // set the size of the viewport, so our screenshot will have the desired size
  await page.setViewport({
      width: 1280,
      height: 800
  })

  await page.goto('https://www.stromonic.com/')
  await page.screenshot({
      path: 'codesnacks.png',
      fullPage: true
  })

  // close the browser 
  await browser.close();
};

// run the async function
run();

 

That snippet will create a screenshot of the whole page, that’s 1280 pixel wide. Of course, you can also set other sizes. The screenshot will be saved in the same directory your script lives in. You can change the directory and name of the file in the path.

That’s a super simple way to create screenshots. Please consider following me, if you’re interested in what else you can do with puppeteer and if you don’t want to miss any of my upcoming articles in this series.

If you enjoyed this article, then you’ll love Stromonic’s WordPress Hosting platform. Turbocharge your website and get 24/7 support from our veteran team. Our world-class hosting infrastructure focuses on auto-scaling, performance, and security. Let us show you the Stromonic difference! Check out our plans.

About the author

Akash Kohli

Akash Kohli is part of the Stromonic marketing team. With years of content writing experience behind him, it's one of his favorite activities. Akash takes part in the SEO of the Stromonic website and blog. His goal is to write comprehensive posts and guides, always aiming to help our clients with essential information. Akash also has a thirst for knowledge and improvement, which makes the hosting environment a perfect place for him.

Email Newsletter

Subscribe to receive inspiration, news, and ideas in your inbox.

TENDING