Google-chrome – How to take a screenshot of a page N seconds after page is loaded with Chrome Headless

google-chromescreenshot

I want to make a screenshot of a page with Chrome Headless, and we've seen both the --screenshot and the --virtual-time-budget switches for taking a screenshot and limiting the browser's waiting for load time.

I have elements on the page however that wait for DOMContentLoaded to render, and we want to capture those too.

I'm looking for a way to take a screenshot, say, 5 seconds after the page is loaded, instead of right when it's considered loaded.

We're calling Chrome Headless from our NodeJS application like so:

cp.spawnSync("google-chrome-beta", ["--headless", "--disable-gpu", "--screenshot", "--profile-directory=Default", "--window-size=1920,6200", "--virtual-time-budget=25000", url]);

We know that there are possible npm libraries that can achieve this using an API from node, instead of using command line switches, but we're concerned about stability (the Chrome team likes to break all their internal APIs regularly).

TL;DR

Is there anyway to make Chrome Headless wait a few seconds after page load before taking a screenshot?

Best Answer

I was looking for the same thing. What I found is google puppeteer. https://github.com/GoogleChrome/puppeteer

There are lots of examples, but basically you can do what I did.

const puppeteer = require('puppeteer');

function timeout(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
};

(async() => {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.setViewport({width: 5960, height: 4209})
    await page.goto('http://stackoverflow.com', {waitUntil: 'networkidle'});
    await timeout(10000)
    await page.screenshot({path: 'example.png'});
    browser.close();

})();