Screenshots 2.0 - Replace PhantomJS with NightmareJS

PhantomJS is nice for really simple stuff like i showed in the PhantomJS-Post. But if you try to do more complicated stuff like: Login first and then make a screenshot ... you better try NightmareJS.

Posted by Fichtl on 25.11.2018

NightmareJS is a high level wrapper for headless-browser and it's much easier to control the browser with it. You install it with: npm install nightmare.

The new screenshot script starts like the other one with the configuration. But then you can simply work with for-loops.

var urls = []; urls.push('http://www.redbull.com/'); urls.push('http://www.karriere.at/'); var sizes = []; sizes.push({width: 1024, height: 768}); sizes.push({width: 768, height: 1024}); sizes.push({width: 640, height: 1024}); sizes.push({width: 320, height: 1024}); var clip = true; var Nightmare = require('nightmare'); for(u in urls) { for(s in sizes) { var nightmare = new Nightmare(); var size = sizes[s]; var filename = 'screen-' + String("0" + u).slice(-2) + '-' + size.width + '.png'; var url = urls[u]; nightmare .viewport(size.width, size.height) .goto(url) .wait() .screenshot(filename) .run(function(err, nightmare){ console.log('Done.'); }); } }

But i want to do some stuff before i make the screenshot ... like a login. There is a use()-method in NightmareJS intended for plugins, but i use it for an encapsulated sub-queue. In the navigate()-function i do the login and then return to the main-queue to take the screenshot.

var urls = []; urls.push('http://www.karriere.at/jobs/javascript'); urls.push('http://www.karriere.at/'); var sizes = []; sizes.push({width: 1024, height: 768}); sizes.push({width: 768, height: 1024}); sizes.push({width: 640, height: 1024}); sizes.push({width: 320, height: 1024}); var email = 'test@test.at'; var password = 'test@test.at-password'; var navigate = function(nightmare) { return function(nightmare) { nightmare .click('#userLogin') .wait(200) .type('#loginForm [name=email]', email) .type('#loginForm [name=password]', password) .click('#submitBtn button') .wait(); }; } var Nightmare = require('nightmare'); for(u in urls) { for(s in sizes) { var nightmare = new Nightmare(); var size = sizes[s]; var filename = 'screen-' + String("0" + u).slice(-2) + '-' + size.width + '.png'; var url = urls[u]; nightmare .viewport(size.width, size.height) .goto(url) .wait() .use(navigate(nightmare)) .screenshot(filename) .run(function(err, nightmare){ console.log('Done.'); }); } }