How to take a screenshot of a webpage with JavaScript?

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.