Skip to content

Instantly share code, notes, and snippets.

@matijagrcic
Forked from paceaux/headless-screenshots.js
Created June 18, 2017 09:15
Show Gist options
  • Save matijagrcic/8c1463f9da6dfc2dba25a6694a6f3027 to your computer and use it in GitHub Desktop.
Save matijagrcic/8c1463f9da6dfc2dba25a6694a6f3027 to your computer and use it in GitHub Desktop.
Screenshot grabber that uses headless chrome (only works on mac)
/** Pre requisites
1) Make an Alias to Chrome
alias chrome="/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome"
alias chrome-canary="/Applications/Google\ Chrome\ Canary.app/Contents/MacOS/Google\ Chrome\ Canary"
2) Make Sure yarn is installed (it caches packages so you don't have to download them again)
`npm i yarn`
3) Use yarn to install dependencies:
`yarn add lighthouse`
`yarn add chrome-remote-interface`
* USAGE:
* `node headless-screenshot.js -w 1024 -h 768 --url=http://google.com`
*/
/* Dependencies */
const chromeLauncher = require('lighthouse/chrome-launcher/chrome-launcher');
const CDP = require('chrome-remote-interface');
const fs = require('fs');
/** ARGUMENTS AND CONFIGUIRATION
* expects arguments to be
* -w int (width)
* -h int (height)
* -p int (port)
* --url string (url)
*/
const argv = require('minimist')(process.argv.slice(2));
const windowWidth = argv.w ? argv.w : 1024;
const windowHeight = argv.h ? argv.h : 1024;
const launchConfig = {
chromeFlags: [
`--window-size=${windowWidth},${windowHeight}`,
'--disable-gpu',
'--headless'
]
}
/** saveScreenshot
*
* @param {String} imageData base64 string
*/
function saveScreenshot(imageData) {
const filename = `${argv.url.replace('http://','').replace(/\//g,'_')}.png`;
fs.writeFile(
filename,
imageData.data, {encoding:'base64'},
(err)=>{
console.warn('error', err);
}
);
}
/**
* Launches a debugging instance of Chrome.
* False launches a full version of Chrome.
* @return {Promise<ChromeLauncher>}
*/
async function launchChrome(headless = true) {
return await chromeLauncher.launch(launchConfig);
}
(async function() {
const chrome = await launchChrome();
const protocol = await CDP({port: chrome.port});
const {Page, Runtime} = protocol;
await Promise.all([Page.enable(), Runtime.enable()]);
Page.navigate({url: argv.url});
Page.loadEventFired(async () => {
const titleJS = "document.querySelector('title').textContent";
const pageTitle = await Runtime.evaluate({expression: titleJS});
const screenshot = await Page.captureScreenshot();
console.log(`title of page: ${pageTitle.result.value}`);
Promise.resolve(screenshot).then((imageData)=>{
saveScreenshot(imageData);
});
protocol.close()
chrome.kill();
});
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment