Getting Started with PhantomJS

Getting Started with PhantomJS

In this PhantomJS tutorial, you'll learn what PhantomJS is 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.

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.

What is PhantomJS

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

Table of Contents

  • Installing PhantomJS
  • PhantomJS Core Concepts
  • PhantomJS in the Wild
  • Conclusion

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.

What is PhantomJS

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,

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.

Conclusion

This article is just an introduction to PhantomJS, in follow-up articles, we will build a screenshot taking application with PhantomJS etc. Stay tuned.

PhantomJS JSON JavaScript WebDev

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

JSON Tutorial For Beginners | What is JSON | Learning JSON with JavaScript

JSON Tutorial For Beginners | What is JSON | Learning JSON with JavaScript

Javascript | How To Covert Javascript Array To JSON

In this example, we will see How To Covert Javascript Array To JSON. We can convert Javascript array to json using JSON.stringify() method. At some point in your time, whatever developer you are, you need to deal with JSON data. JSON stands for Javascript Object Notation. Exchange data between client and server is straightforward using JSON.

JavaScript | Convert JSON String to JSON Object

Convert JSON string to JSON object javascript. This tutorial is the purpose to explain the best ways and examples for convert JSON string to a JSON object.

How to use JSON.stringify() and JSON.parse() in JavaScript

JSON.stringify() and JSON.parse() are useful tools for handling JSON-formatted content

JavaScript Tutorial: if-else Statement in JavaScript

This JavaScript tutorial is a step by step guide on JavaScript If Else Statements. Learn how to use If Else in javascript and also JavaScript If Else Statements. if-else Statement in JavaScript. JavaScript's conditional statements: if; if-else; nested-if; if-else-if. These statements allow you to control the flow of your program's execution based upon conditions known only during run time.