PhantomJS - evaluate()



The evaluate method will execute the function passed to it. If the function contains console messages, it is not displayed directly in the terminal. To display any console messages, you need to use onConsoleMessage phantom callback.

Syntax

Its syntax is as follows −

wpage.evaluate(str)

Example

The following example shows how you can use the evaluate() method.

var wpage = require('webpage').create(); 
wpage.open('http://localhost/tasks/test.html', function(status) { 
   var script1 = "function(){ var a = document.title; return a;}"; 
   var value = wpage.evaluate(script1); 
   console.log(value); 
   phantom.exit(); 
}); 

The above program generates the following output.

Welcome to phantomjs 

Example with Console Messages

Let us consider another example with console messages.

var wpage = require('webpage').create(); 
wpage.onConsoleMessage = function(msg) { 
   console.log('CONSOLE: ' + msg); 
}; 

wpage.open('http://localhost/tasks/test.html', function(status) { 
   var script1 = "function(){ var a = document.title; console.log('hello world');return a;}"; 
   var value = wpage.evaluate(script1); 
   console.log(value); 
   phantom.exit(); 
});

The above program generates the following output.

CONSOLE: hello world 
Welcome to phantomjs
phantomjs_webpage_module_methods.htm
Advertisements