PhantomJS - injectJs()



The injectJs method includes external script from a specified file into the page. If the file is not available in the current directory, it uses libraryPath for additional search of the file. It returns true, if the file is injected, otherwise false.

Syntax

Its syntax is as follows −

wpage.injectJs(filename); 

Example

The following example shows how to use the injectJs() method.

var wpage = require('webpage').create(); 
wpage.open('http://localhost/tasks/a.html', function(status) { 
   if (wpage.injectJs('tscript1.js')) { 
      var msg = wpage.evaluate(function() { 
         return testcode(); 
      }); 
      console.log(msg); 
      phantom.exit(); 
   } 
});

tscript1.js

function testcode () { 
   return "welcome to phantomjs"; 
} 

The above program generates the following output.

welcome to phantomjs 
phantomjs_webpage_module_methods.htm
Advertisements