JavaScript libraries are widely available and can make our coding much easier rather than starting from nothing. PhantomJS supports standard JavaScript, and making use of these libraries is supported. There are two ways to inject external JavaScript into PhantomJS: by using either the phantom
object or the webpage
module.
When external JavaScript is loaded within the phantom
object, we can access the external script within our script globally. When JavaScript is injected within the webpage
object, we can use these libraries with the page document to manipulate or extract data from the loaded page. Regardless of the loading method, the use of these scripts is dependent on how well they are coded and their purpose. For example, injecting jQuery is very useful for manipulating DOM elements.
var page = require('webpage').create(); page.open("https://github.com/", function(status) { if ( status === "success" ) { page.render("before.png"); page.includeJs("http://code.jquery.com/jquery-1.10.1.min.js", function() { page.evaluate(function() { $('.heading').html('PhantomJS'), }); page.render("after.png"); phantom.exit();(); }); } });
In the preceding code, we dynamically include the jQuery JavaScript Library using includeJs
function of the webpage
module. jQuery can be accessing within the page, and using jQuery in the eighth line, denotes that we are replacing a particular DOM element with a new text of PhantomJS
.
Running our code will generate two screenshots of the page: the first screenshot is before modification of the DOM element, and the second is taken after replacing the text on that element.
13.58.190.38