PhantomJS - evaluate() 方法

evaluate 方法将执行传递给它的函数。如果该函数包含控制台消息,则不会直接显示在终端中。要显示任何控制台消息,您需要使用 onConsoleMessage 幻像回调。

语法

其语法如下 −

wpage.evaluate(str)

示例

以下示例展示了如何使用 evaluate() 方法。

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(); 
}); 

上述程序生成以下输出

Welcome to phantomjs 

带有控制台消息的示例

让我们考虑另一个带有控制台消息的示例。

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(); 
});

上述程序生成以下输出。

CONSOLE: hello world 
Welcome to phantomjs

phantomjs_webpage_module_methods.html