PhantomJS - Headless Browser for Screenshots, Testing and more

PhantomJS is a so-called headless browser. That means: It can do everything a "normal" browser can with the little difference that it has no window to display the website.

Posted by Fichtl on 25.07.2015

What for?

You can use it for creating screenshots or you can test your website automatically because PhantomJS can everything that a normal Webkit browser can. You could also build a crawler for javascript-powered websites or you can write performance monitoring scripts. Installation is really simple, just download the archive and extract it ... voila! Now you can now use the bin/phantomjs.

Here the complete and working script, the screenshots will be in the same folder as the script. You can run it with: bin/phantomjs screenshots.js

/** * Configuration */ var urls = []; urls.push('http://www.redbull.com/'); urls.push('http://www.karriere.at/'); urls.push('http://www.michael-feichtinger.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}); /** * if clip is true the screenshot will be cropped to that size * else phantomjs will screenshot the whole website */ var clip = true; /** * All the logic */ var uIdx = 0; var sIdx = 0; var webpage = require("webpage"); function next(uIdx, sIdx) { if(uIdx < urls.length) { screenshot(uIdx, sIdx); } else { phantom.exit(); } } function screenshot(uIdx, sIdx) { var size = sizes[sIdx]; var filename = 'screen-' + String("0" + uIdx).slice(-2) + '-' + size.width + '.png'; var url = urls[uIdx]; var page = webpage.create(); page.viewportSize = size; if (clip) { page.clipRect = { top: 0, left: 0, width: size.width, height: size.height }; } page.open(url, function(){ return window.setTimeout((function() { page.render(filename); page.close(); sIdx++; if(sIdx >= sizes.length) { sIdx = 0; uIdx++; } return next(uIdx, sIdx); }), 200); }); } next(uIdx, sIdx);

Update - Nov. 2018

The development of PhantomJS is abandoned and there are no new features and bugfixes in the future. Look at my post about switching to nightmareJS.