Skip to content

Instantly share code, notes, and snippets.

@malyw malyw/index.js
Last active Mar 19, 2019

What would you like to do?
Capture DOM element screenshot using Chrome headless
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
// Adjustments particular to this page to ensure we hit desktop breakpoint.
page.setViewport({width: 1000, height: 600, deviceScaleFactor: 1});
await page.goto('', {waitUntil: 'networkidle'});
* Takes a screenshot of a DOM element on the page, with optional padding.
* @param {!{path:string, selector:string, padding:(number|undefined)}=} opts
* @return {!Promise<!Buffer>}
async function screenshotDOMElement(opts = {}) {
const padding = 'padding' in opts ? opts.padding : 0;
const path = 'path' in opts ? opts.path : null;
const selector = opts.selector;
if (!selector)
throw Error('Please provide a selector.');
const rect = await page.evaluate(selector => {
const element = document.querySelector(selector);
if (!element)
return null;
const {x, y, width, height} = element.getBoundingClientRect();
return {left: x, top: y, width, height, id:};
}, selector);
if (!rect)
throw Error(`Could not find element that matches selector: ${selector}.`);
return await page.screenshot({
clip: {
x: rect.left - padding,
y: - padding,
width: rect.width + padding * 2,
height: rect.height + padding * 2
await screenshotDOMElement({
path: 'element.png',
selector: 'header aside',
padding: 16

This comment has been minimized.


This comment has been minimized.

Copy link

ashu17706 commented Apr 18, 2018

thanks a lot. 😃
It helped me achieve my current task .


This comment has been minimized.

Copy link

tpai commented Jun 3, 2018

The option {waitUntil: 'networkidle'} of page.goto will cause error on puppeteer@^1.4.0:

ERROR: "networkidle" option is no longer supported. Use "networkidle2" instead.

But after I change to "networkidle2", another error show up:

Error: Protocol error (Runtime.callFunctionOn): Cannot find context with specified id undefined

So I remove the option and everything works fine.


This comment has been minimized.

Copy link

asra-dragonmart commented Nov 14, 2018

worked perfectly!


This comment has been minimized.

Copy link

furtive commented Dec 3, 2018

This could be rewritten (simplified?) now that elementHandle.screenshot([options]) exists.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.