What is PhantomJS and How is it Used?

 

PhantomJS is a headless WebKit scriptable with a JavaScript API. It has fast and native support for various web standards: DOM handling, CSS selector, JSON, Canvas, and SVG.

The above definition may be ambiguous, in simple terms, PhantomJS is a web browser without a graphical user interface.

    In simple terms, PhantomJS is a web browser without a graphical user interface

This then begs the question, What use is a browser without a GUI? A web browser without a graphical user interface is pretty much useless. But because PhantomJS provides a Javascript API, this makes the browser useful. Hence the phrase "WebKit scriptable".
# Installing PhantomJS

Before we learn more about PhantomJS, first you need to install it on your computer. To install PhantomJS, head over to the official website and download the binary suitable for your device.

After downloading the binary, you need to add the executable to PATH environment variable. For Linux users (Mac included), you can place the downloaded binary in usr/bin directory. While Windows users can place the executable in C:\Windows. After doing that, you should be able to open a command prompt or terminal and type phantomjs --help and see a screen like this.

# PhantomJS Core Concepts

Since PhantomJS is not usable when it comes to surfing the web, it has a whole set of features that developers love and use for many purposes.

    Screen capture
    Page automation
    Network monitoring
    Testing
    And more...

Screen Capture

PhantomJS can be used to take screenshots of websites, those screenshots can be rendered in different formats also. Let's spin up a basic javascript script that takes screenshots of a website.

var webpage = require('webpage').create();

webpage.open('https://scotch.io/', function() {
    webpage.render('scotch.png');
    phantom.exit();
});

Running this snippet from a web-browser won't work, we need to load this script using PhantomJS. So we save this snippet in a file screenshot.js, can be anything you want to name it. Then from the command line, run.

phantomjs screenshot.js

Give it a few seconds to run and you should see a file in the same path as screenshot.js named scotch.png, open it and you should see a full page screenshot of scotch.io.
Page Automation

Because we can use PhantomJS to load and manipulate a web page, it is perfect for carrying out page automation. This helps developers run a bunch of tests without ever having to open a web browser.

    Although this may not seem important, this allows us to automate any sort of interactions with a web page without having to open a browser (an operation that will save you a tremendous amount of time).

var webpage = require('webpage').create();

// open scotch.io
webpage.open('https://scotch.io', function(status) {
    if (status !== 'success') {
        console.log('Unable to access network');
    } else {
        var title = webpage.evaluate(function() {
            return document.title;
        });

     // log the title
        console.log(title === 'Scotch | Developers bringing fire to the people.');
    }

    phantom.exit();
});

In the evaluate() method, that's where we write the javascript we want to run on the loaded page. We can save the snippet above in a file and run phantomjs <filename>.js.
Network Monitoring

    Because PhantomJS permits the inspection of network traffic, it is suitable to build various analysis on the network behavior and performance.

We can hook into PhantomJS during a request-response cycle and collect data about the website. This data can be reformatted and allows us to check the performance of a web page.

var page = require('webpage').create();

// hook into initial request
page.onResourceRequested = function(request) {
    console.log('Request ' + JSON.stringify(request, undefined, 4));
};

// hook to response
page.onResourceReceived = function(response) {
    console.log('Receive ' + JSON.stringify(response, undefined, 4));
};

page.open(url);

We can use tools like confess.js (a PhantomJS script) and YSlow for a more in-depth network analysis. This is useful in the sense that we can detect regression in the performance of our website before pushing the code.
Testing

This is an important aspect of software development, but developers rarely talk about. PhantomJS has been made popular as a tool for running unit tests. It can run a lot of tests and show the user the result in the command line. Testing tools like Mocha, Casper, just to mention but a few are good examples of testing with PhantomJS as these tools are based on it.
# PhantomJS in the Wild

PhantomJS is used by many companies, you may have used the product and wondered how it was built. For example, Media Queries (source of inspiration for responsive websites) takes a link, checks if the website is responsive, and shows a preview of the website using different screen sizes. The site was made possible thanks to PhantomJS.

A Spanish Life uses PhantomJS to create ads based on user content. Check Out more examples of PhantomJS.

Twitter uses PhantomJS to run QUnit tests on their website.
Powered by Blogger.