Create WebPage Screenshots with Node.js and PhantomJS
Automation on the web has gotten incredibly accessible and advanced, much in part to utilities like PhantomJS. PhatomJS allows you to do headless WebKit render testing, network monitoring, page automation, and much more. One of the simple tasks I like using PhatomJS for is screenshot creation. Sure I could use another service or another utility but PhantomJS is so flexible and easy to use that there's no need to look elsewhere!
Creating a Screenshot
Assuming you've downloaded PhatomJS, create a JavaScript file (screenshot.js
for example) with the following contents:
var page = require('webpage').create(); page.open('https://davidwalsh.name/', function() { page.render('davidwalshblog.png'); phantom.exit(); });
With that script created, open your command line tool and execute the following:
phantomjs screenshot.js
That's all it takes to create a screenshot of a website!
Setting Viewport Size
PhantomJS makes setting the viewport size easy as well, just one setting to change:
var page = require('webpage').create(); page.viewportSize = { width: 1920, height: 1080 }; page.open('https://davidwalsh.name/', function() { page.render('davidwalshblog1920.png'); phantom.exit(); });
Modifying setting sizes is nice so that you can quickly automate different media query sizes based on your site's specifications!
Every few weeks I'll take screenshots of my site to ensure I've not made any design changes that have broken any of my designs. I'll also use this strategy for creating screenshots of redesign ideas. I love how easy automation of these types of tasks has gotten these days!
It’s worth noting that Phantom uses WebKit as its render engine. Slimer uses Gecko instead, while a headless version of Chrome – directly from Google – is also next to be released.
Alas, nothing decent for Trident or Edge.
Great script for generating screenshots from responsive websites and web applications to see if everything is designed well. Thank you for this blog! :)
If you’d like some more options and easy integration with other code I recommend checking Manet https://github.com/vbauer/manet
Last time I tried node + phantom I ran into a lot of problems around webfont rendering ranging from webfonts not be rendered at all to webfonts partially rendering (with different results each time I ran it) depending on which version of phantom source I built from. At some point I gave up on it and just switched over to browserstack using some of their automated testing functionality.
I’m hoping to revisit phantomjs once the webfont support is more reliable.
Anyone else run into webfont related issues with phantom?
Great tutorial, pity taking an accurate retina screenshot isn’t easy