PhantomJS


I’ve recently switched to using PhantomJS for testing and taking screenshots of web pages, and have come across a few quirks worth noting (besides the lack of WOFF font support, which is annoying but tolerable until they take the plunge and switch to Qt5).

One of the weirdest things was that it would stubbornly refuse to render Github pages properly until I switched the User-Agent string (I still have no idea why).

Regardless, here’s a simplified version of the script I’m currently using for taking web page snapshots that I used to track down that particular bug, since it might be useful to someone else:

var page = require('webpage').create(),
    system = require('system'),
    address, output, size;

if (system.args.length < 3 || system.args.length > 5) {
    console.log('Usage: snap.js URL filename');
    phantom.exit(1);
} else {
    address = system.args[1];
    output = system.args[2];
    page.viewportSize = page.clipRect = { width: 1280, height: 1024 };
    page.customHeaders = {'Referer': address};
    page.settings.javascriptEnabled = true;
    page.settings.localToRemoteUrlAccessEnabled = true;
    page.settings.XSSAuditingEnabled = true;
    page.settings.webSecurityEnabled = true;
    // this fails on Github
    page.settings.userAgent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/536.28.10 (KHTML, like Gecko) Version/6.0.3 Safari/536.28.10';
    // this works on Github
    page.settings.userAgent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.116 Safari/537.36';
    page.open(address, function (status) {
        if (status !== 'success') {
            console.log('Unable to load the address!');
            phantom.exit();
        } else {
            window.setTimeout(function () {
                page.render(output);
                phantom.exit();
            }, 7500);
        }
    });
}