- PhantomJS is built on top of webkit layout and rendering engine.
- In this demo “We will learn to capture screenshot from a given URL using PhantomJS”.
- It provides support for JSON,DOM handling,CSS support,canvas and svg.
- PhantomJS can be installed locally using npm install phantomjs –save command.The following screenshot shows the terminal with phantomjs installation.
- To demonstrate PhantomJS we have created PhantomJSDemo project.The following screenshot shows the directory structure of PhantomJSDemo.
- The app.js file contains the code which loads the webpage module provided by PhantomJS and creates page instance using create() method.The open() method is used to find the specified URL( for this demo it is Google website) and on success it capture as image using render() method.The code content of app.js file is as follows:-
var page = require('webpage').create(); page.open('http://google.com/', function(status) { if(status === "success"){ console.log("URL Found"); page.render('google.png'); }else{ console.log("URL not found") } phantom.exit(); });
- This example can be run using phantomjs app.js command.The following screenshot shows the terminal with PhantomJS in execution.
- On successful execution of this command we can find the google.png file got create in the same working directory.The following screenshot shows the updated project structure with the google.png file.
- The google.png file looks like following screenshot.
- The demo code can be downloaded from the following URL.
https://github.com/saan1984/PhantomJSDemo