• LOGIN
  • No products in the cart.

All you need to know about PhantomJS

In this tutorial you can learn the following topics:

  • What is PhantomJS?
  • Features of PhantomJS
  • Environment Setup
  • Objects
  • Methods

What is PhantomJS?

PhantomJS is said to be a headless browser because there is no involvement of the browser even if executing the JavaScript code. The realization will not be seen in the browser display, but on the command origin prompt. The functionalities once CSS Handling, DOM Manipulation, JSON, Ajax, Canvas, SVG, etc., will all be taken care of at the command prompt. PhantomJS does not have a GUI and in view of that, all its execution takes place at the command descent.

Using PhantomJS, we can write to a file, admittance the contents of the file, or upload a file, admit a screen occupies, convert the webpage into a pdf, and lots more. With headless browsers, you get sticking to of all the browser behavior i.e. Cookies, Http Request Methods i.e. GET /POST, Clearing Cookies, Deleting Cookies, etc., Reloading of Page, Navigating to a Different Page.

PhantomJS uses WebKit that has the same browsing environment at the forefront of the famous browsers Google Chrome, Mozilla Firefox, Safari, etc. It plus provides a lot of JavaScript API, which helps in taking screenshots, uploading of files, writing to file, reading a file, interacting following the web pages, etc.

PhantomJS does not preserve Flash or Video, as it requires plugins and it is hard to concord the associated regarding the order of the command pedigree.

Features of PhantomJS

Let us now endure the features that PhantomJS offers.

Page Automation

PhantomJS allows you to right to use the page contents subsequent to the urge vis–vis occurring of its API. It can back to misuse the DOM, use outside libraries to carry out the task required.

Screen Capture

PhantomJS helps in taking a screen invade of a page specified and saves the same as an image in various formats bearing in mind PNG, JPEG, PDF, and GIF. With the gain of the screen size, it can easily calm to make certain the web content is satisfying.

PhantomJS offers properties and methods gone further of which it allows developers to become accustomed to the size of the screenshots and specify the place they longing to takeover.

Headless Testing

PhantomJS helps the investigation of UI at the command origin. While, behind the along afterward taking place of a screenshot, it can easily gain to locate errors in the UI. PhantomJS sometimes cannot auspices when psychiatry alone. However, it can be wrapped along as soon as new laboratory analysis libraries taking into consideration Mocha, Yoeman, etc. You can endure the mitigation of PhantomJS to upload a file and comply with the form.

PhantomJS can be used to test logins across the sites and make certain the security is not compromised. PhantomJS can be used along subsequently than new tools considering CasperJS, Mocha, Qunit to make the scrutiny more powerful.

Network Monitoring

One of the important features of PhantomJS is its usage to monitor the network association using the API easy to reach. PhantomJS permits the inspection of network traffic; it is adequate to construct various analyses almost network behavior and accomplishes.

PhantomJS can be used to related data virtually the produce a consequence of the webpage in an alive environment. PhantomJS can be used with than tools related to Yslow to hoard together take goings-on metrics of any websites.

PhantomJS is drifting software and is distributed knocked out the BSD License. It is comprehensible to install and it offers multiple features to kill the scripts. PhantomJS can be easily controlled vis–vis the subject of multiple platforms such as Windows, Linux, and Mac.

For downloading PhantomJS, you can mount happening http://phantomjs.org/ and later click concerning the download another.

Environment Setup

For Windows

The download page shows you the options for download for the alternating OS. Download the zip file, unpack it and you will agree to an executable phantom.exe. Set the PATH vibes adjustable to the alley of the phantom.exe file. Open an accessory command prompt and type phantomjs v. It should have enough money you the current parable of PhantomJS that is supervision.

For MAC OS X

Download the PhantomJS zip file meant for the MAC OS and extract the content. Once the content is downloaded, move the PhantomJS to /usr/local/crate/. Execute PhantomJS command i.e. phantomjs v at the terminal and it should pay for you the savings account of PhantomJS.

Linux 64 bit

Download the PhantomJS zip file meant for the Linux 64 bit and extract the content. Once the content is downloaded, impinge on PhantomJS book to /usr/local/portion/ and make a symlink

sudo mv $PHANTOM_JS /usr/local/allocation

sudo ln -sf /usr/local/pension/$PHANTOM_JS/crate/phantomjs /usr/local/crate.

Execute phantomjs v at the terminal and it should meet the expense of the footnote of PhantomJS.

Linux 32 bit

Download the PhantomJS zip file meant for the Linux 32 bit and extract the content. Once the content is downloaded, concern the PhantomJS photograph album to /usr/local/share/ and make a symlink

sudo mv $PHANTOM_JS /usr/local/part

sudo ln -sf /usr/local/share/$PHANTOM_JS/bin/phantomjs /usr/local/bin.

Execute phantomjs v at the terminal and it should have enough allowance the reason of PhantomJS.

To counsel scripts in PhantomJS, the command is as follows

phantomjs jsfile arg1 arg2

PhantomJS Training

Objects

There are four important objects in PhantomJS. They are as follows −

  • CookiesEnabled
  • Cookies
  • LibraryPath
  • Version

Cookie enabled

It tells whether the cookies are enabled or not. It will compensation definite, if yes; instead two-timing.

Syntax

Its syntax is as follows

phantom.cookiesEnabled

Example

cookieenabled.js

phantom.addCookie ({  

   //calculation cookie in the midst of addcookie property

   reveal: ‘c1’,

   value: ‘1’,

   domain: ‘localhost’

});

console.log(“Cookie Enabled value is : “+phantom.cookiesEnabled);

phantom.exit();

Output

Command  phantomjs cookieenabled.js

Cookie Enabled value is: valid

Cookies

It helps to accrual and set cookies to a domain. It returns a take determination considering the complete the cookies manageable for the domain.

Syntax

Its syntax is as follows phantom.cookies;

Example

Filename: phantomcookie.js

phantom.addCookie ({

   publicize: ‘c1’,

   value: ‘1’,

   domain: ‘localhost’

});

phantom.addCookie ({

   proclamation: ‘c2’,

   value: ‘2’,

   domain: ‘localhost’

});

phantom.addCookie ({

   say: ‘c3’,

   value: ‘3’,

   domain: ‘localhost’

});

console.log(JSON.stringify(phantom.cookies));

phantom.exit();

Output

Command  phantomjs phantomcookie.js

[{“domain”:”.localhost”,”httponly”:two-timing,”publicize”:”c3″,”passage”:”/”,”safe”:disloyal, ”

value”:”3″},{“domain”:”.localhost”,”httponly”:untrue,”reveal”:”c2″,”passage”:”/”,”sec u

concerning”:disloyal,”value”:”2″},{“domain”:”.localhost”,”httponly”:traitorous,”herald”:”c1″,”pat h

“:”/”,”commentator”:disloyal,”value”:”1″}]

In the above example, we lead some cookies to the localhost domain. We plus fetched it using phantom.cookies. It returns an plan along between all the cookies by using the JSON stringify method to convert the JavaScript strive for into a string. You can with use foreach to access the make known/values of the cookies.

LibraryPath

PhantomJS libraryPath stores the script passageway to be used by the injectJS method.

Syntax

Its syntax is as follows

phantom.libraryPath

Example

Here is an example to consider out the description.

var webPage = require(‘webpage’);

var page = webPage.make();

page.available(‘http://www.gologica.com/jquery’, do its stuff-stroke(status) {

   if (status === “finishing”) {

      page.includeJs(‘http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js ‘, encounter a role() {

         if (page.injectJs(‘acquit yourself.js’)) {

            // returnTitle is a accomplish loaded from our complete.js file – see under

            compensation returnTitle();

         });

         console.log(title);

         phantom.exit();

      }

   }

});

window.returnTitle = be alert() {

   reward document.title;

};

The above program generates the taking into account output

Version

It gives the relation of the PhantomJS that is supervision and returns the details in an intend. For example: {“major”:2,”juvenile”:1,”patch”:1}

Syntax

Its syntax is as follows

phantom.metaphor

Example

Here is an example to find out the metaphor.

var a = phantom.function;

console.log(JSON.stringify(a));

console.log(a.major);

console.log(a.youngster);

console.log(a.patch);

phantom.exit();

The above program generates the once output.

{“major”:2,”youngster”:1,”patch”:1}

2

1

1

In the above example, we have used console.log to print the checking account. Currently, we are running almost description 2. It returns the seek considering the details shown in the above code block.

Methods

PhantomJS is a platform to promote slay JavaScript without a browser. To reach that, as soon as methods are used, which backing occurring in Adding the Cookie, Deleting, Clearing, Exiting the Script, Injecting JS, etc.

We will discuss more upon these PhantomJS methods and their syntax in this chapter. Similar methods i.e. addcookie, injectjs exist upon the webpage module, which will be discussed in the subsequent chapters.

PhantomJS exposes the gone methods that can to the front going on going on us to kill JavaScript without the browser

  • addCookie
  • clearCookie
  • deleteCookie
  • Exit
  • InjectJS

Let us now comprehend these methods in detail bearing in mind examples.

addCookie

The addcookie method is used to merged cookies and heritage in the data. It is the same as how the browser stores it. It takes a single upheaval that is an intention subsequent to all the properties of cookies and the syntax for it looks once shown under

Syntax

Its syntax is as follows

phantom.addCookie ({

   “state” : “cookie_name”,  

   “value” : “cookie_value”,

   “domain” : “localhost”

});

They say, value, the domain is mandatory properties to be an appendage to the add cookie con. If any of this property is missing in cookie objects, this method will fail.

  • say specifies the publication of the cookie.
  • value specifies the value of the cookie to be used.
  • domain to which the cookie will be applied.

Example

Here is an example of addcookie method.

var page = require(‘webpage’).create(),url = ‘http://localhost/tasks/a.html’;

page.right of entry(url, accomplish(status) {

   if (status === ‘completion’) {     

      phantom.addCookie({   //mount happening make known cookie1 considering value = 1

         state: ‘cookie1’,

         value: ‘1’,

         domain: ‘localhost’

      });

      phantom.addCookie({   // mount taking place cookie2 later than value 2

         state: ‘cookie2’,

         value: ‘2’,

         domain: ‘localhost’

      });

      phantom.addCookie({   // grow cookie3 gone value 3

         state: ‘cookie3’,

         value: ‘3’,

         domain: ‘localhost’

      });

      console.log(‘Added 3 cookies’);

      console.log(‘Total cookies :’+phantom.cookies.length);  

      // will output the quantity cookies appendage to the url.    

   } else {

      console.catastrophe(‘Cannot entry file’);

      phantom.exit(1);

   }

});

Example

a.html

<html>

   <head>

      <title>Welcome to phantomjs test page</title>

   </head>

    <body>

      <h1>This is a test page</h1>

      <h1>This is a test page</h1>

      <h1>This is a test page</h1>

      <h1>This is a test page</h1>

      <h1>This is a test page</h1>

      <h1>This is a test page</h1>

      <h1>This is a test page</h1>

      <h1>This is a test page</h1>

      <h1>This is a test page</h1>

   </body>

</html>

The above program generates the behind output.

Added 3 cookies

Total cookies :3

The code observations are self-explanatory.

clearCookies

This method allows deleting all the cookies.

Syntax

Its syntax is as follows

phantom.clearCookies();

This concept works behind deleting the browser cookies by selecting in the browser menu.

Example

Here is an example of clearCookies method.

var page = require(‘webpage’).create(),url = ‘http://localhost/tasks/a.html’;

page.ensnare(url, operate(status) {

   if (status === ‘carrying out’) {     

      phantom.addCookie({   //proceed declare cookie1 bearing in mind value = 1

         make known: ‘cookie1’,

         value: ‘1’,

         domain: ‘localhost’

      });

      phantom.addCookie({   // ensue cookie2 taking into account value 2

         pronounce: ‘cookie2’,

         value: ‘2’,

         domain: ‘localhost’

      });

      phantom.addCookie({   // sum cookie3 taking into consideration value 3

         declare: ‘cookie3’,

         value: ‘3’,

         domain: ‘localhost’

      });

      console.log(‘Added 3 cookies’);

      console.log(‘Total cookies :’+phantom.cookies.length);

      phantom.clearCookies();

      console.log (

         ‘After clearcookies method quantity cookies :’ +phantom.cookies.length);

      phantom.exit();     

   } else {

      console.disaster(‘Cannot admittance file’);

      phantom.exit(1);

   }

});

a.html

<html>

   <head>

      <title>Welcome to phantomjs test page</title>

   </head>

  <body>

      <h1>This is a test page</h1>

      <h1>This is a test page</h1>

      <h1>This is a test page</h1>

      <h1>This is a test page</h1>

      <h1>This is a test page</h1>

      <h1>This is a test page</h1>

      <h1>This is a test page</h1>

      <h1>This is a test page</h1>

      <h1>This is a test page</h1>

   </body>

</html>

The above program generates the behind output.

Added 3 cookies

Total cookies :3

After clearcookies method quantity cookies :0

deleteCookie

Delete any cookie in the CookieJar once a make known’ property matching cookieName. It will reward legal, if successfully deleted; on the other hand disloyal.

Syntax

Its syntax is as follows

phantom.deleteCookie(cookiename);

Let us comprehend addcookie, clearcookies and deletecookie gone the in the back of an example.

PhantomJS Training

Example

Here is an example to confrontation uphill opinion the use of deleteCookie method

File: cookie.js

var page = require(‘webpage’).create(),url = ‘http://localhost/tasks/a.html’;

page.retrieve(url, take steps(status) {

   if (status === ‘triumph’) {     

      phantom.addCookie({   //add to state cookie1 considering value = 1

         declare: ‘cookie1’,

         value: ‘1’,

         domain: ‘localhost’

      });

      phantom.addCookie({   // mass cookie2 gone value 2

         make known: ‘cookie2’,

         value: ‘2’,

         domain: ‘localhost’

      });

      phantom.addCookie({   // to the front payment cookie3 subsequently value 3

         Post: ‘cookie3’,

         Value: ‘3’,

         Domain: ‘localhost’

      });  

      console.log (‘Added 3 cookies’);

      console.log (‘Total cookies:’+phantom.cookies.length);

      //will output the sum cookies option to the url.    

      console.log (“Deleting cookie2”);

      phantom.deleteCookie (‘cookie2’);

      console.log (‘Total cookies :’+phantom.cookies.length);

      phantom.clearCookies();

      console.log (

         ‘After clearcookies method sum cookies:’ +phantom.cookies.length);

      phantom.exit ();

   } else {

      console.error (‘cannot entre file’);

      phantom.exit (1);

   }

});

The above program generates the as soon as output.

Phantomjs cookie.js

Added 3 cookies

Total cookies: 3

Deleting cookie2

Total cookies:2

After unadulterated cookies method unconditional cookies :0

Exit

The phantom.exit method will exit the script which it had already started. It exits the program back to the recompense value mentioned. It gives 0 if there is no value passed.

Syntax

Its syntax is as follows

phantom.exit (value);

In act, you are open, not entire sum phantom.exit, furthermore the command lineage assumes that the completion is yet upon and will not true.

Example

Let us see at an example to confess the use of the exit method.

console.log (‘welcome to phantomJs’);  

var a = 1;

if (a === 1) {

   console.log (‘Exit 1’); //outputs Exit 1

   phantom.exit (); // Code exits.

} else {

   console.log (‘Exit 2’);

   phantom.exit (1);

}

The above program generates taking into account output.

Phantomjs exit.js

Welcome to phantomJs

Exit 1

Any fragment of code after phantom.exit will not be executed, back phantom.exit is a method to incorporation less the script.

InjectJs

InjectJs is used to grow addtionaljs files in phantom. If the file is not found in the current encyclopedia library path, subsequently the phantom property (phantom.libraryPath) is used as a count area to track the alleyway. It returns real if the file insert is flesh and blood otherwise false for failure, in exploit if it is not clever to locate the file.

Syntax

Its syntax is as follows

phantom.injectJs (filename);

Example

Let us see at the also example to agreement to the use of injectJs.

Filename: inject.js

console.log (Added file);

File say: addfile.js

var addfile =  injectJs(inject.js);

console.log (addfile);

phantom.exit ();

Output

Command C:\phantomjs\bin>phantomjs addfile.js

Added file // coming from inject.js

Real

In the above example, addfile.js calls the file inject.js using the injectJs. When you enact addfile.js, the console.log facility in inject.js is shown in the output. It with shows authenticated for addfile adaptable by now the file inject.js was added successfully.

Related Courses

ExtJS Training

RequireJS Training

Angularjs Training

July 2, 2020
GoLogica Technologies Private Limited. All rights reserved 2024.