Data, Maps, Usability, and Performance

Using CasperJS to Make MultiBrowser Screenshots

Last updated on July 17, 2012 in Development

render screenshots in casperjs

Update: As pointed out in the comments, we are only changing a user-agent string not the rendering engine. IE Conditional comments are enabled through the IE rendering engine so sending an IE user-agent will not give you a real IE screenshot. With that being said, you can use SlimmerJS to render Gecko (browser engine of Mozilla Firefox) screenshots instead of WebKit.

CasperJS is an awesome testing utility for PhantomJS, a headless WebKit browser. In other words, it is something like Selenium, a tool for you to automate a browser, but written in JavaScript instead of Java. It basically allows you to run all kinds of tests on your website and log the information or render screenshots. It comes packaged with a sample script for making a screenshot, but what if you wanted to make a couple screenshots per page based on different browsers (different user agent string).

Well, if you look at the CasperJS API you can see a userAgent example but this example does not work. It is not very obvious at first as the example seems to be working when run (you get the expected print statements in the console). However, if you include a callback on resource requested and retrieve the User-Agent string for each resource, you quickly realize that both tests have been done with the same last user agent string. Look at the output of this example code:

Clearly, the issue is that CasperJS processes all the code first and when thenOpen actually opens a webpage, the last userAgent definition is used by PhantomJS to retrieve the page. So, to fix this, we need to pause the execution for some time using wait() function before using another user-agent and re-opening the same page. The following casperjs script will correctly make screenshots for any web page with different browsers. I have used the user-agent strings from my previous article.

Tags: , , , ,

Facebook Twitter Hacker News Reddit More...