PhantomJS – Child Process Module

Webpage Child Process Module ”; Previous Next The Phantomjs Child process module helps to interact with the sub-processes and talk to them using stdin /stdout/stderr. The child processes can be used for tasks like printing, sending mail or to invoke programs written in another language. To create a child process module, you need references. For example − var process = require(“child_process”); Spawn Method With the spawn child process, you can subscribe to its stdout and stderr streams to get data real-time. Syntax Its syntax is as follows − var spawn = require(”child_process”).spawn; Example Let us look at an example of the spawn method. var process = require(“child_process”) var spawn = process.spawn var child = spawn(“cmd”, [”/c”, ”dir”]); child.stdout.on(“data”, function (data) { console.log(“spawnSTDOUT—VALUE:”, JSON.stringify(data)) }) child.stderr.on(“data”, function (data) { console.log(“spawnSTDERR:”, JSON.stringify(data)) }) child.on(“exit”, function (code) { console.log(“spawnEXIT:”, code) }) Output The above program generates the following output. spawnSTDOUT—VALUE: ” Volume in drive C is OSrn” spawnSTDOUT—VALUE: ” Volume Serial Number is 7682-9C1Brnrn Directory of C: \phantomjs\binrnrn” spawnSTDOUT—VALUE: “20-05-2017 10:01 <DIR> .rn20-05-2017 10:01 <DIR> ..rn13-05-2017 20:48 12 a,txt.txtrn07-05-2017 08:51 63 a.jsrn06-05-2017 16:32 120,232 a.pdfrn13-05-2017 20:49 spawnEXIT: 0 Print Page Previous Next Advertisements ”;

PhantomJS – Properties

PhantomJS – Web Server Module Properties ”; Previous Next PhantomJS uses an embedded web server called mongoose. Right now, PhantomJS cannot connect with any other production webserver. With respect to connection, it can deal with 10 connections at a time and more than 10 requests will be waiting in a queue. To start a webserver, we need to use the following syntax − var webserver = require (‘webserver’); Let us understand the Port property, which is used to listen to the requests that are sent to the webserver. port The Port property for a webserver is used to listen to the request that are sent to it. Syntax Its syntax is as follows − var server = require(”webserver”).create(); var listening = server.listen(port, function (request, response) {}); Example Let us take an example to understand how the port property works. var webserver = require(”webserver”); var server = webserver.create(); var service = server.listen(8080,function(request,response){ }); if(service) console.log(“server started – http://localhost:” + server.port); The above program generates the following output. server started – http://localhost:8080 Print Page Previous Next Advertisements ”;

PhantomJS – Examples

PhantomJS – Examples ”; Previous Next In this chapter, we are providing a few more practical examples to understand some important features of PhantomJS. Example 1 – Find the Page Speed In this example, we will use PhantomJS to find the page speed for any given page URL. var page = require(”webpage”).create(), system = require(”system”), t, address; if (system.args.length === 1) { console.log(”Usage: loadspeed.js <some URL>”); phantom.exit(1); } else { t = Date.now(); address = system.args[1]; page.open(address, function (status) { if (status !== ”success”) { console.log(”FAIL to load the address”); } else { t = Date.now() – t; console.log(”Page title is ” + page.evaluate(function () { return document.title; })); console.log(”Loading time ” + t + ” msec”); } phantom.exit(); }); } The above program generates the following output. Command − phantomjs pagespeed.js http://www.google.com Page title is Google Loading time 1396 msec Example 2 – Send a Click Event to a Page In the following example, we will use PhantomJS to send a click event to a page. var page = require(”webpage”).create(); page.onConsoleMessage = function(str) { console.log(str); } page.open(”http://phantomjs.org/api/phantom/”, function(status) { page.render(”beforeclick.png”); console.log(page.url); var element = page.evaluate(function() { return document.querySelector(”img[src = “http://phantomjs.org/img/phantomjslogo.png”]”); }); page.sendEvent(”click”, element.offsetLeft, element.offsetTop, ”left”); window.setTimeout(function () { console.log(page.url); page.render(”afterclick.png”); phantom.exit(); }, 5000); console.log(”element is ” + element); }); The above program generates the following output. http://phantomjs.org/api/phantom/ element is [object Object] http://phantomjs.org/ Our program will create the following two png images in the bin folder. These two images show the difference before and after the execution of the above program. Example 3 – Submit a Form The following example shows how to submit a form using PhantomJS. var wpage = require(”webpage”).create(); wpage.open(“http://localhost/tasks/submitform.html”, function(status) { console.log(status); wpage.uploadFile(”input[name = fileToUpload]”, ”output.png”); wpage.render(“sform.png”); var element = wpage.evaluate(function() { return document.querySelector(”input[type = “submit”]”); // getting details of submit button using queryselector. }); wpage.sendEvent(”click”, element.offsetLeft, element.offsetTop, ”left”); // sendevent is used to send click event and also giving the left and top position of the submit button. window.setTimeout(function () { console.log(wpage.url); wpage.render(“submit.png”); // screenshot is saved in submit.png phantom.exit(); }, 5000); console.log(”element is ” + element); }); submitform.html The following code shows how to use the submitform.html file. <html> <head> <title>Window 2</title> </head> <body> <form action = “submitform.php” method = “post” enctype = “multipart/form-data” id = “form1”> <input type = “file” name = “fileToUpload” id = “fileToUpload”> <input type = “submit” value = “Upload Image” name = “submit”> </form> </body> </html> Once the form is submitted, it goes to submitform.php. submitform.php submitform.php is just printing the details of the files. <?php print_r($_FILES); ?> The above program generates the following output. Success element is [object Object] http://localhost/tasks/submitform.php Images Following are the images for file upload and form submit. Print Page Previous Next Advertisements ”;

PhantomJS – Discussion

Discuss PhantomJS ”; Previous Next PhantomJS is a lightweight headless browser built on WebKit. It is called headless because the execution does not happen on the browser, but on the terminal. This tutorial covers most of the topics required for a basic understanding of PhantomJS. Additionally, this tutorial also explains how to deal with its various components and to get a feel of how it works. Print Page Previous Next Advertisements ”;

PhantomJS – Screen Capture

PhantomJS – Screen Capture ”; Previous Next PhantomJS is very helpful in taking a screenshot of a webpage and converting a webpage into a PDF. We have given here a simple example to demonstrate how it works. Example var page = require(”webpage”).create(); page.open(”http://phantom.org/”,function(status){ page.render(”phantom.png”); phantom.exit(); }); Execute the above program and the output will be saved as phantom.png. Convert Webpages into PDFs PhantomJS also helps to convert webpages into PDFs with header and footer added to it. Take a look at the following example to understand how it works. var wpage = require(”webpage”).create(); var url = “https://en.wikipedia.org/wiki/Main_Page”; var output = “test.pdf”; wpage.paperSize = { width: screen.width+”px”, height: ”1500px”, margin: { ”top”:”50px”, ”left”:”50px”, ”rigtht”:”50px” }, orientation:”portrait”, header: { height: “1cm”, contents: phantom.callback(function(pageNumber, nPages) { return “<h5>Header <b>” + pageNumber + ” / ” + nPages + “</b></h5>”; }) }, footer: { height: “1cm”, contents: phantom.callback(function(pageNumber, nPages) { return “<h5>Footer <b>” + pageNumber + ” / ” + nPages + “</b></h5>”; }) } } wpage.open(url, function (status) { if (status !== ”success”) { console.log(”Page is not opening”); phantom.exit(); } else { wpage.render(output); phantom.exit(); } }); The above program generates the following output. The above will convert the page into pdf and will be saved in test.pdf Convert a Canvas to an Image Phantomjs can easily convert a Canvas to an Image. Take a look at the following example to understand how it works. var page = require(”webpage”).create(); page.content = ”<html><body><canvas id=”surface” width=”400″ height=”400″></canvas></body></html>”; page.evaluate(function() { var context,e1; el = document.getElementById(”surface”); context = el.getContext(”2d”); context.font = “30px Comic Sans MS”; context.fillStyle = “red”; context.textAlign = “center”; context.fillText(“Welcome to PhantomJS “, 200, 200); document.body.style.backgroundColor = ”white”; document.body.style.margin = ”0px”; }); page.render(”canvas.png”); phantom.exit(); The above program generates the following output. Print Page Previous Next Advertisements ”;

PhantomJS – Methods

PhantomJS – Webpage Module Methods ”; Previous Next The Web Page Module has methods for Cookies, Frames, Page Navigation, Reload, Rendering and Uploading of Files. Following are the methods available on the web page. S.No Methods & Description 1 addCookie() addCookie method adds cookies to the page specified. 2 childFramesCount() This method is deprecated as per http://phantomjs.org. 3 childFramesName() This method is deprecated as per http://phantomjs.org. 4 clearCookies() Will delete all the cookies for the page specified. 5 close() This method is used to close the page and release the memory used. Any of the webpage methods or properties will not work once the close is called. 6 currentFrameName() This method is deprecated as per http://phantomjs.org. 7 deleteCookie() This will delete a cookie with the name matching with the existing list of cookies present for a given page url. 8 evaluateAsync() Evaluate given function asynchronously within the page without blocking current execution. This function helps to execute certain scripts asynchronously. 9 evaluateJavascript() EvaluateJavaScript helps to execute the function passed to it as a string. Please note the string passed has to be a function only. 10 evaluate() Evaluate will execute the function passed to it. If the function contain console messages it is not displayed directly in the terminal. To display any console messages you need to use onConsoleMessage phantom callback. 11 getPage() This will give you the child page that matches the windowname passed in getpage. 12 goBack() It gives the previous page in navigation history, if only the navigation is not locked. 13 goForward() It gives the next page in navigation history, if only the navigation is not locked. 14 go() This method allows you to navigate with the pages. 15 includeJs() Includejs executes the external JS file on page and executes the callback function on completion. 16 injectJs() InjectJs includes external script from a specified file into the page. If the file is not available in the current directory, then it used libraryPath for additional search of the file. It returns true if the file is injected, otherwise false. 17 openUrl() OpenUrl opens up a webpage. It is similar to open method of PhantomJS. OpenUrl has some additional parameters, which are httpConf, settings and callback functions. 18 open() Open is used to open up a webpage. 19 release() Release will release the memory heap usage for the page. Do not use page instance methods after the release is called. This method is similar to the close method and the usage of it is deprecated. Instead use wpage.close(). 20 reload() Reload is used to reload the current page used. 21 renderBase64() This method takes the screen capture and gives the image as a string in base46. Renderbase64 supports format like PNG, JPEG and JPG. It does not support gif as of now. You can use clipRect property to define the portion for image capture. 22 renderBuffer() RenderBuffer takes the capture of the webpage to an image buffer, which can be directly sent to the server. Formats supported are PNG, GIF and JPEG. 23 render() Render helps to take the image buffer and save it as per the format specified. 24 sendEvent() It is used to send an event to the webpage. They are not dom events. Each of these events are sent to the webpage based on user interaction. 25 setContent() setcontent will change the page content of the specified url with the contents specified. 26 stop() It helps to stop loading of the page. 27 switchToChildFrame() It is deprecated to use switchToFrame(); 28 switchToFocusedFrame() It selects the frame, which is in focus. 29 switchToFrame() Selects frame with the name specified and which is child of current frame. 30 switchToMainFrame() Selects mainframe i.e. the root window. 31 switchToParentFrame() It takes the parent frame of the current child frame. 32 uploadFile() This method is used to handle the file upload done using form in html. PhantomJS does not have a direct way to do so using forms the same can be achieved using uploadFile method. It takes html tag selector for file location and the destination where it has to be copied. Print Page Previous Next Advertisements ”;

PhantomJS – Methods

PhantomJS – File System Module Methods ”; Previous Next The following table has all the methods and their descriptions, which are available on the File System module. S.No Methods & Description 1 absolute This method gives the absolute path where PhantomJS runs. 2 changeWorkingDirectory This allows you to change the working directory and returns true, if it succeeds otherwise returns false. 3 copyTree copyTree will copy a directory from one path to another. The first parameter is a source folder and the second parameter is a destination folder. 4 copy This method helps to copy file from one location to another. It takes two parameters. The first parameter is the source file and the second parameter is the file path, where it has to be copied. It will throw an error, if the source or destination file does not exist. 5 exists It checks whether the given file path exists in the system. It returns true, if it is present, otherwise false. 6 isAbsolute This method will return true, if the file path is absolute and false, if relative. 7 isDirectory isDirectory tells if the given file is a directory or not. It returns true, if directory otherwise false. It gives false in case if the given path does not exist. 8 isExecutable This method will tell if the given file is executable or not. It returns true, if executable, otherwise false. 9 isFile This gives details whether the filepath given is a file or not. It returns true, if it is a file and false, if it is not. 10 isLink This will give you true, if the file path is a symlink, otherwise false. 11 isReadable It checks if the given file is readable or not. It gives true, if yes and false, if not. 12 isWritable It tells whether if a given file is writable. Returns true, if yes, otherwise false. 13 lastModified Gives the details of the last modification done to the file. It tells the date and time of when the file was last modified. 14 list It gives all the files present in the directory. 15 makeDirectory Creates a new directory. 16 makeTree makeTree creates all necessary folders to be able to form final directories. This will return true, if the creation was successful, otherwise false. If the directory already exists, it will return true. 17 move It will move the file from one path to another. 18 open It is used to open up the file. 19 readLink This will return the absolute path of a file or a folder pointed by a symlink (or shortcut on Windows). If the path is not a symlink or shortcut, it will return an empty string. 20 read This will read the given file. 21 removeDirectory This will remove the given directory. 22 removeTree It will delete all the files and folders from the given folder and finally delete the folder itself. If there is any error while doing this process, it will throw an error – ”Unable to remove directory tree PATH” and hang execution. 23 remove It removes the given file. 24 size It gives the size of the file. 25 touch It creates a given file. 26 write Writes to a given file. Print Page Previous Next Advertisements ”;

PhantomJS – Properties

PhantomJS – File System Module Properties ”; Previous Next The File System Module has many APIs to deal with files and directories. You can create/write and delete a file/directory. To start using the file system module you must require a reference to the fs module. var fs = require(”fs”); There are two properties available for file system module: Separator and Working Directory. Let us understand them in detail. Separator It tells you the separator used for the file paths. For windows: For Linux: / Syntax Its syntax is as follows − fs.seperator Example var fs = require(”fs”); console.log(fs.seperator); phantom.exit(); The above program generates the following output. undefined workingDirectory The working directory is the directory in which PhantomJS executes. Syntax Its syntax is as follows − var fs = require(”fs”); fs.workingDirectory; Example var fs = require(”fs”); console.log(fs.workingDirectory); phantom.exit(); The above program generates the following output. C:/phantomjs/bin Print Page Previous Next Advertisements ”;

PhantomJS – Environment Setup

PhantomJS – Environment Setup ”; Previous Next PhantomJS is a free software and is distributed under the BSD License. It is easy to install and it offers multiple features to execute the scripts. PhantomJS can be easily run on multiple platforms such as Windows, Linux, and Mac. For downloading PhantomJS, you can go to – http://phantomjs.org/ and then click on the download option. For Windows The download page shows you the options for download for different OS. Download the zip file, unpack it and you will get an executable phantom.exe. Set the PATH environment variable to the path of phantom.exe file. Open a new command prompt and type phantomjs –v. It should give you the current version of PhantomJS that is running. For MAC OS X Download the PhantomJS zip file meant for MAC OS and extract the content. Once the content is downloaded, move the PhantomJS to – /usr/local/bin/. Execute PhantomJS command i.e. phantomjs –v at the terminal and it should give you the version description of PhantomJS. Linux 64 bit Download the PhantomJS zip file meant for Linux 64 bit and extract the content. Once the content is downloaded, move PhantomJS folder to /usr/local/share/ and create a symlink − sudo mv $PHANTOM_JS /usr/local/share sudo ln -sf /usr/local/share/$PHANTOM_JS/bin/phantomjs /usr/local/bin. Execute phantomjs –v at the terminal and it should give the version of PhantomJS. Linux 32 bit Download the PhantomJS zip file meant for Linux 32 bit and extract the content. Once the content is downloaded, move the PhantomJS folder to /usr/local/share/ and create a symlink − sudo mv $PHANTOM_JS /usr/local/share sudo ln -sf /usr/local/share/$PHANTOM_JS/bin/phantomjs /usr/local/bin. Execute phantomjs –v at the terminal and it should give the version of PhantomJS. The PhantomJS source code can also be taken from the git repository by clicking on the following link – https://github.com/ariya/phantomjs/ To run scripts in PhantomJS, the command is as follows − phantomjs jsfile arg1 arg2… Print Page Previous Next Advertisements ”;