Writing PhantomJS scripts
We know how to write JavaScript, and now we know that there are several PhantomJS JavaScript APIs and objects. We also have learned the basics of the PhantomJS command-line arguments. We are now ready to create our own scripts.
We will create a simple script to load a site and then display the title of the page when loaded successfully. Finally, we will exit. If the page fails to load, we will log some message to the console.
var page = require('webpage').create(); page.open("http://www.packtpub.com", function(status) { if ( status === "success" ) { console.log(page.title); } else { console.log("Page failed to load."); } phantom.exit(0); });
The preceding PhantomJS script is very simple. First, we import the webpage
module, create an instance of the webpage
object, and assign it to a variable named page
.
The page
variable now holds an instance of the webpage
module where an open
function is available. Next, we instructed PhantomJS through the webpage
instance to open and load the URL. The second parameter of the open
function is a function callback definition that will be executed upon completion of the opening of the URL. Inside the definition, we check if the status is "success
", and if it is, the page is loaded, and then we will display the title of the page. Then, we call the exit
function to terminate the script. Let's save this code snippet as helloweb.js
and execute it by passing the filename as our first argument to the phantomjs
binary.