Created
March 5, 2012 15:59
-
-
Save ryanmark/1978977 to your computer and use it in GitHub Desktop.
Easy responsive screenshots with Phantom.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Take a set of full height screenshots for a range of screensizes. | |
* phantomjs responsive-screens.js http://www.cnn.com/ png | |
* | |
* This will create a directory tree in your current directory which | |
* mirrors the URL. All files will be named with the current time. | |
* You can run this on a cron to build an archive of screenshots. | |
**/ | |
var page = new WebPage(), | |
address, output, size, filename_parts, ext, filename, dirs; | |
var fs = require('fs'); | |
var now = new Date(); | |
var viewports = [ | |
{ width: 1200, height: 800 }, | |
{ width: 1024, height: 768 }, | |
{ width: 768, height: 1024 }, | |
{ width: 480, height: 640 }, | |
{ width: 320, height: 480 } | |
] | |
if (phantom.args.length < 2 || phantom.args.length > 3) { | |
console.log('Usage: responsive-screens.js URL png|pdf'); | |
phantom.exit(); | |
} else { | |
address = phantom.args[0]; | |
dir = url_to_dir(address); | |
ext = phantom.args[1]; | |
page.viewportSize = viewports[0]; | |
output = dir + "/" + date_string() + "-" + viewports[0].width + "." + ext; | |
page.open(address, function (status) { | |
if (status !== 'success') { | |
console.log('Unable to load the address!'); | |
} else { | |
window.setTimeout(function () { | |
console.log('Saving '+output+'...'); | |
page.render(output); | |
for (var i=1; i<viewports.length; i++) { | |
page.viewportSize = viewports[i]; | |
output = dir + "/" + date_string() + "_" + viewports[i].width + "." + ext; | |
console.log('Saving '+output+'...'); | |
page.render(output); | |
} | |
phantom.exit(); | |
}, 200); | |
} | |
}); | |
} | |
function url_to_dir( url ) { | |
var dir; | |
dir = url.replace('http://', ''); | |
if (dir.charAt(dir.length-1) == '/') dir = dir.substr(0, dir.length-2); | |
fs.makeTree(dir); | |
return dir; | |
} | |
function date_string() { | |
var month = now.getMonth()+1, | |
day = now.getDate(), | |
minutes = now.getMinutes(); | |
if ( month < 10 ) month = '0'+month; | |
if ( day < 10 ) day = '0'+day; | |
if ( minutes < 10 ) minutes = '0'+minutes; | |
return [now.getFullYear(), month, day].join('-') + "_" + [now.getHours(), minutes].join(':'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment