Categories
JavaScript Answers

How to take a screenshot of a webpage with JavaScript?

Spread the love

Sometimes, we want to take a screenshot of a webpage with JavaScript.

In this article, we’ll look at how to take a screenshot of a webpage with JavaScript.

How to take a screenshot of a webpage with JavaScript?

To take a screenshot of a webpage with JavaScript, we can use Puppeteer.

To install it, we run

npm i puppeteer

Then we use it by writing

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" });

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

to call browser.newPage to open a new page.

Then we go to https://example.com with page.goto.

Then we take a screenshot and save it to example.png with page.screenshot.

Finally, we close the browser with browser.close.

Conclusion

To take a screenshot of a webpage with JavaScript, we can use Puppeteer.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *