Skip to content

Instantly share code, notes, and snippets.

@paceaux
Last active May 13, 2024 06:34
Show Gist options
  • Save paceaux/353fc20eb6e21098b0ef09f86db2d188 to your computer and use it in GitHub Desktop.
Save paceaux/353fc20eb6e21098b0ef09f86db2d188 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, pageURL) {
const filename = `${pageURL.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 saveScreenShotFromURL(pageURL) {
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: pageURL});
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,pageURL);
});
protocol.close();
chrome.kill();
});
}
saveScreenShotFromURL(argv.url)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment