PhantomJS – Useful Resources

PhantomJS – Useful Resources ”; Previous Next The following resources contain additional information on PhantomJS. Please use them to get more in-depth knowledge on this. Useful Video Courses Full Stack Development With Vue JS 2 And Spring Boot 54 Lectures 3.5 hours Senol Atac More Detail Node js for Course for beginners + Game project 27 Lectures 2.5 hours Laurence Svekis More Detail Advanced Theoretical JavaScript: Learn Advanced JS Concepts 25 Lectures 2 hours Mehul Mohan More Detail ReactJS Course : Learn React JS From Scratch Best Seller 61 Lectures 4.5 hours Skillbakery More Detail JavaScript Deep Dive: Explore JS (For Beginners-to-Advanced) 129 Lectures 5.5 hours TELCOMA Global More Detail React JS and .NET Core Web API Full Stack Master Course 21 Lectures 3.5 hours Vinay Kumar More Detail Print Page Previous Next Advertisements ”;

PhantomJS – REPL

PhantomJS – REPL ”; Previous Next REPL stands for Read Eval Print Loop. In PhantomJS, REPL is an interactive mode to test the JavaScript code. You can do the same thing, which is done in Google Chrome Inspector or Firebug to execute some piece of code directly on the console. REPL returns you the same platform to execute the scripts. The typed command is sent to the interpreter for immediate interpretation (EVAL) and to provide feedback (PRINT). Enter PhantomJS in the command line and it will take you to the interactive mode, where you can execute your code directly. Syntax Its syntax is as follows − Phantomjs Example The following example demonstrates how REPL works in PhantomJS. phantomjs> console.log(“Welcome to phantomjs”); Welcome to phantomjs Undefined phantomjs> window.navigator { “appCodeName”: “Mozilla”, “appName”: “Netscape”, “appVersion”: “5.0 (Windows NT 6.2; WOW64) AppleWebKit/538.1 (KHTML, like Gecko) PhantomJS/2.1.1 Safari/538.1”, “cookieEnabled”: true, “language”: “en-IN”, “mimeTypes”: { “length”: 0 }, “onLine”: false, “platform”: “Win32”, “plugins”: { “length”: 0 }, “product”: “Gecko “productSub”: “20030107”, “userAgent”: “Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/538.1 (KHTML, like Gecko) PhantomJS/2.1.1 Safari/538.1”, “vendor”: “Apple Computer, Inc.”, “vendorSub”: “” } phantomjs> To find the version phantomjs> phantom.version { “major”: 2, “minor”: 1, “patch”: 1 } phantomjs> Each command is executed and the result is displayed. Use CTRL+C, CTRL+D or phantom.exit() to come out of the interactive mode. Use the up/down arrow keys to listen to the previously typed commands. There is another feature called autocompletion, which helps to remember the command. Just type “phantom” and hit the “Tab” button to get a list of available commands you can execute. Output The above program generates the following output. phantomjs> phantom.→| phantomjs> phantom.cookies→| phantomjs> phantom.exit→| phantomjs> phantom.version→| Print Page Previous Next Advertisements ”;

PhantomJS – Methods

PhantomJS – Web Server Module Methods ”; Previous Next In this chapter, we will discuss regarding the various methods of the Web Server Module of PhantomJS. close The close method is used to close the webserver. Syntax Its syntax is as follows − var server = require(”webserver”).create(); server.close(); Example The following example shows how you can use the close method. 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); console.log(server.port); server.close(); console.log(server.port); The above program generates the following output. server started – http://localhost:8080 8080 Here, we have consoled server.port after closing the server. Hence, it will not respond, as the webserver is already closed. listen The server.listen method takes the port and callback function with two arguments, which are – Request Object and Response Object. The Request Object contains the following properties − Method − This defines the method GET /POST. URL − This displays the requested URL. httpVersion − This displays the actual http version. Headers − This displays all the headers with key value pairs. Post − Request body applicable only for the post method. postRaw − If the Content-Type header is set to ”application/x-www-formurlencoded”, the original content of the post will be stored in this extra property (postRaw) and then that post will be automatically updated with a URL-decoded version of the data. The Response Object contains the following properties − Headers − Has all the HTTP headers as key-value pairs. It should be set before calling write for the first time. SetHeader − This sets a specific header. Header (name) − It returns the value of the given header. StatusCode − It sets the returned HTTP status code. SetEncoding (encoding) − This is used to convert data given to write(). By default, data will be converted to UTF-8. Indicate “binary” if data is a binary string. Not required if data is a Buffer (e.g. from page.renderBuffer). Write (data) − It sends data for the response body. Can be called multiple times. WriteHead (statusCode, headers) − It sends a response header to the request. The status code is a 3-digit HTTP status code (e.g. 404). The last arguments and headers are the response headers. Close − It closes the http connection. CloseGracefully − It is similar to close(), but it makes sure the response headers have been sent first. Syntax Its syntax is as follows − var server = require(”webserver”).create(); var listening = server.listen(8080, function (request, response) {} Example Let us take an example to understand how the listen method works. var page = require(”webpage”).create(); var server = require(”webserver”).create(); var port = 8080; var listening = server.listen(8080, function (request, response) { console.log(“GOT HTTP REQUEST”); console.log(JSON.stringify(request, null, 4)); // we set the headers here response.statusCode = 200; response.headers = {“Cache”: “no-cache”, “Content-Type”: “text/html”}; // the headers above will now be sent implictly // now we write the body response.write(“<html><head><title>Welcone to Phantomjs</title></head>”); response.write(“<body><p>Hello World</p></body></html>”); response.close(); }); if (!listening) { console.log(“could not create web server listening on port ” + port); phantom.exit(); } var url = “http://localhost:” + port + “/foo/response.php”; console.log(“sending request to :” +url); page.open(url, function (status) { if (status !== ”success”) { console.log(”page not opening”); } else { console.log(“Getting response from the server:”); console.log(page.content); } phantom.exit(); }); The above program generates the following output. sending request to :http://localhost:8080/foo/response.php GOT HTTP REQUEST { “headers”: { “Accept”: “text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8”, “Accept-Encoding”: “gzip, deflate”, “Accept-Language”: “en-IN,*”, “Connection”: “Keep-Alive”, “Host”: “localhost:8080”, “User-Agent”: “Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/538.1 (KHTML, like Gecko) PhantomJS/2.1.1 Safari/538.1” }, “httpVersion”: “1.1”, “method”: “GET”, “url”: “/foo/response.php” } Getting response from the server: <html><head><title>Welcone to Phantomjs</title></head><body><p>Hello World</p></body> </html> Print Page Previous Next Advertisements ”;

PhantomJS – Quick Guide

PhantomJS – Quick Guide ”; Previous Next PhantomJS – Overview PhantomJS is said to be a headless browser because there is no involvement of browser while executing the JavaScript code. The execution will not be seen in the browser display, but on the command line prompt. The functionalities like CSS Handling, DOM Manipulation, JSON, Ajax, Canvas, SVG, etc., will all be taken care at the command prompt. PhantomJS does not have a GUI and hence, all its execution takes place at the command line. Using PhantomJS, we can write to a file, read the contents of the file or upload a file, take an screen capture, convert the webpage into a pdf and lots more. With headless browsers, you get 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 a similar browsing environment like the famous browsers – Google Chrome, Mozilla Firefox, Safari, etc. It also provides a lot of JavaScript API, which helps in taking screenshots, uploading of file, writing to file, reading a file, interacting with the web pages, etc. PhantomJS does not support Flash or Video, as it requires plugins and it is difficult to support the same on the command line. Features of PhantomJS Let us now understand the features that PhantomJS offers. Page Automation PhantomJS allows you to read the page contents with the help of its API. It can help to manipulate the DOM, use external libraries to carry out the task required. Screen Capture PhantomJS helps in taking a screen capture of a page specified and save the same as an image in various formats like PNG, JPEG, PDF, and GIF. With the help of the screen capture, it can easily help to make sure the web content is fine. PhantomJS offers properties and methods with the help of which it allows developers to adjust the size of the screenshots and specify the area they want to capture. Headless Testing PhantomJS helps testing of UI at the command line. While, with the help of a screenshot, it can easily help to find errors in the UI. PhantomJS sometimes cannot help with testing alone. However, it can be wrapped along with other testing libraries like Mocha, Yoeman, etc. You can take the help of PhantomJS to upload a file and submit the form. PhantomJS can be used to test logins across the sites and make sure the security is not compromised. PhantomJS can be used along with other tools like CasperJS, Mocha, Qunit to make the testing more powerful. Network Monitoring One of the important features of PhantomJS is its usage to monitor the network connection using the API available. PhantomJS permits the inspection of network traffic; it is suitable to build various analysis on the network behavior and performance. PhantomJS can be used to collect the data about the performance of the webpage in a live environment. PhantomJS can be used with tools like Yslow to gather performance metrics of any websites. PhantomJS – Environment Setup 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… PhantomJS – Object In this chapter, we will look at the four important objects PhantomJS. They are as follows − CookiesEnabled Cookies LibraryPath Version Let us now discuss each of these in detail. cookiesEnabled It tells whether the cookies are enabled or not. It will return true, if yes; otherwise false. Syntax Its syntax is as follows − phantom.cookiesEnabled Example cookieenabled.js phantom.addCookie ({ //adding cookie with addcookie property name: ”c1”, value: ”1”, domain: ”localhost” }); console.log(“Cookie Enabled value is : “+phantom.cookiesEnabled); phantom.exit(); Output Command − phantomjs cookieenabled.js Cookie Enabled value is : true Cookies It helps to add and set cookies to a domain. It returns an object with all the cookies available for the domain. Syntax Its syntax is as follows − phantom.cookies; Example Filename: phantomcookie.js phantom.addCookie ({ name: ”c1”, value: ”1”, domain: ”localhost” }); phantom.addCookie ({ name: ”c2”, value: ”2”, domain: ”localhost” }); phantom.addCookie ({ name: ”c3”, value: ”3”, domain: ”localhost” }); console.log(JSON.stringify(phantom.cookies)); phantom.exit(); Output Command − phantomjs phantomcookie.js [{“domain”:”.localhost”,”httponly”:false,”name”:”c3″,”path”:”/”,”secure”:false, ” value”:”3″},{“domain”:”.localhost”,”httponly”:false,”name”:”c2″,”path”:”/”,”sec u re”:false,”value”:”2″},{“domain”:”.localhost”,”httponly”:false,”name”:”c1″,”pat h “:”/”,”secure”:false,”value”:”1″}] In the above example, we added

PhantomJS – Object

PhantomJS – Object ”; Previous Next In this chapter, we will look at the four important objects PhantomJS. They are as follows − CookiesEnabled Cookies LibraryPath Version Let us now discuss each of these in detail. cookiesEnabled It tells whether the cookies are enabled or not. It will return true, if yes; otherwise false. Syntax Its syntax is as follows − phantom.cookiesEnabled Example cookieenabled.js phantom.addCookie ({ //adding cookie with addcookie property name: ”c1”, value: ”1”, domain: ”localhost” }); console.log(“Cookie Enabled value is : “+phantom.cookiesEnabled); phantom.exit(); Output Command − phantomjs cookieenabled.js Cookie Enabled value is : true Cookies It helps to add and set cookies to a domain. It returns an object with all the cookies available for the domain. Syntax Its syntax is as follows − phantom.cookies; Example Filename: phantomcookie.js phantom.addCookie ({ name: ”c1”, value: ”1”, domain: ”localhost” }); phantom.addCookie ({ name: ”c2”, value: ”2”, domain: ”localhost” }); phantom.addCookie ({ name: ”c3”, value: ”3”, domain: ”localhost” }); console.log(JSON.stringify(phantom.cookies)); phantom.exit(); Output Command − phantomjs phantomcookie.js [{“domain”:”.localhost”,”httponly”:false,”name”:”c3″,”path”:”/”,”secure”:false, ” value”:”3″},{“domain”:”.localhost”,”httponly”:false,”name”:”c2″,”path”:”/”,”sec u re”:false,”value”:”2″},{“domain”:”.localhost”,”httponly”:false,”name”:”c1″,”pat h “:”/”,”secure”:false,”value”:”1″}] In the above example, we added some cookies to the localhost domain. We then fetched it using phantom.cookies. It returns an object with all the cookies by using the JSON stringify method to convert the JavaScript object into a string. You can also use foreach to access the name/values of the cookies. LibraryPath PhantomJS libraryPath stores the script path to be used by the injectJS method. Syntax Its syntax is as follows − phantom.libraryPath Example Here is an example to find out the version. var webPage = require(”webpage”); var page = webPage.create(); page.open(”http://www.tutorialspoint.com/jquery”, function(status) { if (status === “success”) { page.includeJs(”http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js ”, function() { if (page.injectJs(”do.js”)) { // returnTitle is a function loaded from our do.js file – see below return returnTitle(); }); console.log(title); phantom.exit(); } } }); window.returnTitle = function() { return document.title; }; The above program generates the following output. Jquery Tutorial Version It gives the version of the PhantomJS that is running and returns the details in an object. For example: {“major”:2,”minor”:1,”patch”:1} Syntax Its syntax is as follows − phantom.version Example Here is an example to find out the version. var a = phantom.version; console.log(JSON.stringify(a)); console.log(a.major); console.log(a.minor); console.log(a.patch); phantom.exit(); The above program generates the following output. {“major”:2,”minor”:1,”patch”:1} 2 1 1 In the above example, we have used console.log to print the version. Currently, we are running on version 2. It returns the object with the details shown in the above code block. Print Page Previous Next Advertisements ”;

PhantomJS – Home

PhantomJS Tutorial PDF Version Quick Guide Resources Job Search Discussion 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. Audience This tutorial is designed for those programmers who want to learn the basics of PhantomJS and its programming concepts. It will give you enough understanding on various functionalities of PhantomJS with suitable examples. Prerequisites Before proceeding with this tutorial, you should have a basic understanding of HTML, CSS, JavaScript, and Document Object Model (DOM). Print Page Previous Next Advertisements ”;

PhantomJS – Methods

PhantomJS – Methods ”; Previous Next PhantomJS is a platform to help execute JavaScript without a browser. To do that, the following methods are used, which help in Adding the Cookie, Deleting, Clearing, Exiting the Script, Injecting JS, etc. We will discuss more on these PhantomJS methods and their syntax in this chapter. Similar methods i.e. addcookie, injectjs exists on the webpage module, which will be discussed in the subsequent chapters. PhantomJS exposes the following methods that can help us to execute JavaScript without the browser − addCookie clearCookie deleteCookie Exit InjectJS Let us now understand these methods in detail with examples. addCookie The addcookie method is used to add cookies and store in the data. It is similar to how the browser stores it. It takes a single argument that is an object with all the properties of cookies and the syntax for it looks like shown below − Syntax Its syntax is as follows − phantom.addCookie ({ “name” : “cookie_name”, “value” : “cookie_value”, “domain” : “localhost” }); The name, value, domain are mandatory properties to be added to the addcookie function. If any of this property is missing in the cookie objects, this method will fail. name − specifies the name of the cookie. value − specifies the value of the cookie to be used. domain − domain to which the cookie will be applied. Example Here is an example of the addcookie method. var page = require(”webpage”).create(),url = ”http://localhost/tasks/a.html”; page.open(url, function(status) { if (status === ”success”) { phantom.addCookie({ //add name cookie1 with value = 1 name: ”cookie1”, value: ”1”, domain: ”localhost” }); phantom.addCookie({ // add cookie2 with value 2 name: ”cookie2”, value: ”2”, domain: ”localhost” }); phantom.addCookie({ // add cookie3 with value 3 name: ”cookie3”, value: ”3”, domain: ”localhost” }); console.log(”Added 3 cookies”); console.log(”Total cookies :”+phantom.cookies.length); // will output the total cookies added to the url. } else { console.error(”Cannot open 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 following output. Added 3 cookies Total cookies :3 The code comments are self-explanatory. clearCookies This method allows deleting all the cookies. Syntax Its syntax is as follows − phantom.clearCookies(); This concept works similar to deleting the browser cookies by selecting in the browser menu. Example Here is an example of the clearCookies method. var page = require(”webpage”).create(),url = ”http://localhost/tasks/a.html”; page.open(url, function(status) { if (status === ”success”) { phantom.addCookie({ //add name cookie1 with value = 1 name: ”cookie1”, value: ”1”, domain: ”localhost” }); phantom.addCookie({ // add cookie2 with value 2 name: ”cookie2”, value: ”2”, domain: ”localhost” }); phantom.addCookie({ // add cookie3 with value 3 name: ”cookie3”, value: ”3”, domain: ”localhost” }); console.log(”Added 3 cookies”); console.log(”Total cookies :”+phantom.cookies.length); phantom.clearCookies(); console.log( ”After clearcookies method total cookies :” +phantom.cookies.length); phantom.exit(); } else { console.error(”Cannot open 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 following output. Added 3 cookies Total cookies :3 After clearcookies method total cookies :0 deleteCookie Delete any cookie in the CookieJar with a ‘name” property matching cookieName. It will return true, if successfully deleted; otherwise false. Syntax Its syntax is as follows − phantom.deleteCookie(cookiename); Let us understand addcookie, clearcookies and deletecookie with the help of an example. Example Here is an example to demonstrate the use of deleteCookie method − File: cookie.js var page = require(”webpage”).create(),url = ”http://localhost/tasks/a.html”; page.open(url, function(status) { if (status === ”success”) { phantom.addCookie({ //add name cookie1 with value = 1 name: ”cookie1”, value: ”1”, domain: ”localhost” }); phantom.addCookie({ // add cookie2 with value 2 name: ”cookie2”, value: ”2”, domain: ”localhost” }); phantom.addCookie({ // add cookie3 with value 3 name: ”cookie3”, value: ”3”, domain: ”localhost” }); console.log(”Added 3 cookies”); console.log(”Total cookies :”+phantom.cookies.length); //will output the total cookies added to the url. console.log(“Deleting cookie2″); phantom.deleteCookie(”cookie2”); console.log(”Total cookies :”+phantom.cookies.length); phantom.clearCookies(); console.log( ”After clearcookies method total cookies :” +phantom.cookies.length); phantom.exit(); } else { console.error(”Cannot open file”); phantom.exit(1); } }); The above program generates the following output. phantomjs cookie.js Added 3 cookies Total cookies :3 Deleting cookie2 Total cookies :2 After clearcookies method total cookies :0 Exit The phantom.exit method will exit the script which it had started. It exits the program with return value mentioned. It gives ‘0’, if there is no value passed. Syntax Its syntax is as follows − phantom.exit(value); In case you do not add phantom.exit, then the command line assumes that the execution is still on and will not complete. Example Let us look at an example to understand the use of the exit method. console.log(”Welcome to phantomJs”); // outputs 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 the following output. phantomjs exit.js Welcome to phantomJs Exit 1 Any piece of code after phantom.exit will not be executed, since phantom.exit is a method to end the script. injectJs InjectJs is used to add addtionaljs files in phantom. If the file is not found in the current directory librarypath, then the phantom property (phantom.libraryPath) is used as an additional place to track the path. It returns true if the file addition is successful otherwise false for failure, incase if it is not able to locate the file. Syntax Its syntax is as follows − phantom.injectJs(filename); Example Let us look at the following example to understand the use of injectJs. Filename: inject.js

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 – Events/Callbacks

Webpage Module Events/Callbacks ”; Previous Next The callbacks available with the webpage module are described in the following table. S.No Callbacks & Description 1 onAlert() This callback is called when there is an alert on the page; the callback takes a string and does not return anything. 2 onCallback() OnCallback is used to pass values from webpage to webpage object and it is done using the window.callPhantom() method, which internally invokes the onCallback function. 3 onClosing() This is called when the window is closed either by using the page.close() method or the window.close() method. 4 onConfirm() This callback is called when there is a confirmed message called with ok /cancel from the page. 5 onConsoleMessage() This callback is used when there are console messages used in the webpage. The onConsoleMessage method takes 3 arguments. 6 onError() It is called when there is JavaScript error. The arguments for onError are msg and stack trace, which is an array. 7 onFilePicker() This is used for upload file the callback is called when user want to upload a file. 8 onInitialized() This callback is invoked when the page is called before loading. 9 onLoadFinished() This function is called when the page opened is fully loaded. It has one argument, which tells when loading was a success or a failure. 10 onLoadStarted() This callback is invoked when the page starts loading. 11 onNavigationRequested() This callback tells when the navigation event is taking place. 12 onPageCreated() This callback is invoked when a new child window is opened by the page. 13 onPrompt() This callback is called when a prompt is called by the web page. It takes 2 arguments, message and the answer. The return value is a string. 14 onResourceError() This callback is called when the webpage is not able to upload the file. 15 onResourceReceived() This callback is called when the resource requested by the page is received. 16 onResourceRequested() This function is invoked when page requests a resource. 17 onResourceTimeout() This callback is called when the requested resource times out, when settings.resourceTimeout is used. 18 onUrlChanged() This is called when the URL changes from the current one using navigation. It has one argument to the call back, which is a new URL targetUrl string. Print Page Previous Next Advertisements ”;