Grunt and PhantomJS, sitting in a tree


Grunt and PhantomJS, sitting in a tree.

The best way to understand how this lib should be used is by looking at the grunt-contrib-qunit plugin. Mainly, look at how the lib is required, how event handlers are bound and how PhantomJS is actually spawned.

Also, in the case of the grunt-contrib-qunit plugin, it's important to know that the page being loaded into PhantomJS doesn't know it will be loaded into PhantomJS, and as such doesn't have any PhantomJS->Grunt code in it. That communication code, aka. the "bridge", is dynamically injected into the html page.

  • timeout: PhantomJS' timeout, in milliseconds.
  • inject: JavaScript to inject into the page.
  • page: an object of options for the PhantomJS page object.
  • screenshot: saves a screenshot on failure

If a Grunt task looked something like this:

grunt.registerTask('mytask', 'Integrate with phantomjs.', function() {
  var phantomjs = require('grunt-lib-phantomjs').init(grunt);
  var errorCount = 0;
  // Handle any number of namespaced events like so. 
  phantomjs.on('mytask.ok', function(msg) {
  phantomjs.on('mytask.error', function(msg) {
  // Create some kind of "all done" event. 
  phantomjs.on('mytask.done', function() {
  // Built-in error handlers. 
  phantomjs.on('fail.load', function(url) {
    grunt.warn('PhantomJS unable to load URL.');
  phantomjs.on('fail.timeout', function() {
    grunt.warn('PhantomJS timed out.');
  // This task is async. 
  var done = this.async();
  // Spawn phantomjs 
  phantomjs.spawn('test.html', {
    // Additional PhantomJS options. 
    options: {},
    // Complete the task when done. 
    donefunction(err) {
      done(err || errorCount === 0);

And test.html looked something like this (note the "bridge" is hard-coded into this page and not injected):

<!doctype html>
// Send messages to the parent PhantomJS process via alert! Good times!!
function sendMessage() {
  var args = [];
sendMessage('mytask.ok', 'Something worked.');
sendMessage('mytask.error', 'Something failed.');

Then running Grunt would behave something like this:

$ grunt mytask
Running "mytask" task
Something worked.
>> Something failed.
Warning: Task "mytask" failed. Use --force to continue.
Aborted due to warnings.

PhantomJS requires these dependencies on Ubuntu/Debian:

apt-get install libfontconfig1 fontconfig libfontconfig1-dev libfreetype6-dev