Skip to content

Instantly share code, notes, and snippets.

@leegee
Created November 11, 2013 06:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leegee/7408781 to your computer and use it in GitHub Desktop.
Save leegee/7408781 to your computer and use it in GitHub Desktop.
Take a screenshot with Phantom.js under Node.js
/*
Take a screenshot with Phantom.js under Node.js
APIs
* Phantom https://github.com/ariya/phantomjs/wiki/API-Reference
* Webpage https://github.com/ariya/phantomjs/wiki/API-Reference-WebPage
*/
var page = require('webpage').create();
if (phantom.args.length < 2){
console.log('Usage: screenshot.js URL filename [quoted-selector] [username:password]');
console.log(' eg: screenshot.js http://www.google.co.uk temp.png');
console.log(' eg: screenshot.js http://www.google.co.uk region.png "#container"');
console.log(' eg: screenshot.js https://www.freedharma.com region.png "#container" username:mypassword');
phantom.exit(1);
}
var args = {
uri : phantom.args[0],
path : phantom.args[1],
selector : phantom.args[2] || null,
credentials : phantom.args[3] || null
};
if (args.credentials != null){
page.customHeaders={'Authorization': 'Basic '+btoa(args.credentials)};
// Buggy:
// page.settings.userName = username;
// page.settings.password = password;
}
console.log("Running with "+args.uri+" "+args.path+" "+args.selector);
page.open(args.uri, function (status) {
if (status !== 'success') {
console.log('Unable to load the uri, '+args.uri);
phantom.exit(1);
}
else {
window.setTimeout(function () {
// Ineffective?
page.viewportSize = { width: '1280px', height: '1280px' };
if (args.selector){
var clipRect = page.evaluate(function( args ) {
document.body.style.width = '1280px';
try {
return document.querySelector(args.selector).getBoundingClientRect();
}
catch (e) {
console.error(e);
console.log("Unable to fetch bounds for element " + args.selector +" for "+args.uri);
return null;
}
}, args);
}
else {
console.log('No selector');
}
if (clipRect) page.clipRect = clipRect;
page.render(args.path);
phantom.exit(0);
}, 500);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment