Skip to content

Instantly share code, notes, and snippets.

@usepe
Last active August 29, 2015 14:18
Show Gist options
  • Save usepe/db1c7cde8fc3131b2d2b to your computer and use it in GitHub Desktop.
Save usepe/db1c7cde8fc3131b2d2b to your computer and use it in GitHub Desktop.
CasperJS: Shoot Page
var casper = require('casper').create(),
config = {
timeout: 5000,
middle: '',
clipRect: true
},
url = 'http://localhost/',
prefix = 'app-seen',
viewports = require('viewports.json').viewports,
passedOptions = casper.cli.options,
passedArgs = casper.cli.args;
if (passedArgs.length > 1) {
casper.echo('Just one url at a time please.', 'info');
casper.echo('Usage: casperjs shoot-page.js <url>', 'info');
casper.exit(1);
}
if (passedArgs.length) {
url = passedArgs[0];
}
if (passedOptions.timeout) {
config.timeout = (function () {
try {
return parseInt(passOptions.timeout);
} catch (e) { }
return config.timeout;
}());
}
if (passedOptions.middle) {
config.middle = passedOptions.middle + '-';
}
if (passedOptions.noClip) {
config.clipRect = 'false';
}
casper
.start(url, function () {
this.echo('Landing at: ' + this.getCurrentUrl() + '.', 'info');
})
.each(viewports, function (casper, viewport) {
var clipArea = {
top: 0,
left: 0,
width: viewport.width,
height: viewport.height
};
this
.then(function () {
this.viewport(viewport.width, viewport.height);
})
.thenOpen(url, function () {
this.wait(config.timeout);
})
.then(function () {
this.echo('[Screenshot] ' + viewport.name, 'info');
this.capture(
'screenshots/' + prefix + '-' + config.middle + viewport.name + '.png',
config.clipRect ? clipArea : null
);
});
})
.run();
var page = require('webpage').create(),
viewports = require('./viewports.json').viewports,
finishedLoading = false,
timeout = 5000,
url = '<insert-something>';
function takeShoot (viewports, index) {
page.viewportSize = {
width: viewports[index].width,
height: viewports[index].height
};
page.onResourceRequested = function (request) {
clearTimeout(finishedLoading);
};
page.onResourceReceived = function (response) {
finishedLoading = setTimeout(function () {
page.render('screenshots/' + viewports[index].name + '.png');
index++;
if (index < viewports.length) {
takeShoot(viewports, index);
} else {
phantom.exit();
}
}, timeout);
};
page.open(url);
}
takeShoot(viewports, 0);
{
"viewports": [
{
"name": "320x480",
"width": 320,
"height": 480
},
{
"name": "360x640",
"width": 360,
"height": 640
},
{
"name": "768x1024",
"width": 768,
"height": 1024
},
{
"name": "800x1280",
"width": 800,
"height": 1280
},
{
"name": "980x1280",
"width": 980,
"height": 1280
},
{
"name": "1280x600",
"width": 1280,
"height": 600
},
{
"name": "1920x900",
"width": 1920,
"height": 900
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment