javascript console.log 在 CasperJS 中不起作用,使用 setTimeout 进行评估
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11864373/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
console.log doesn't work in CasperJS' evaluate with setTimeout
提问by Rustem
Why when I use console.log
in evaluate
, it works:
为什么当我使用console.log
in 时evaluate
,它有效:
casper.then(function() {
this.evaluate( function() {
console.log('hello');
});
});
But this doesn't work:
但这不起作用:
casper.then(function() {
this.evaluate( function() {
setTimeout( function() {console.log('hello');}, 1000);
});
});
回答by NiKo
Because you're mixing up casperjs and remote page environments. The evaluate
function will execute code within the remote page env, so the console.log
call won't output anything.
因为您正在混淆 casperjs 和远程页面环境。该evaluate
函数将在远程页面环境中执行代码,因此console.log
调用不会输出任何内容。
If you want to catch remoteconsole.log
calls, listen to the remote.message
event:
如果要捕获远程console.log
调用,请收听remote.message
事件:
casper.on('remote.message', function(msg) {
this.echo('remote message caught: ' + msg);
})
Btw, documentation for eventsis pretty much exhaustive, as well as the one for evaluate.
回答by odigity
@NiKo's answer is critical.
@NiKo 的回答很关键。
I would also suggest adding the following, since if there's an error, you might not even make it far enough to print out a console.log() msg, and instead end up with silence.
我还建议添加以下内容,因为如果出现错误,您甚至可能无法打印出 console.log() msg,而最终会保持沉默。
casper.on( 'page.error', function (msg, trace) {
this.echo( 'Error: ' + msg, 'ERROR' );
});
回答by pius
CasperJS includes ClientUtils, which can be used from the remote page to easily log to the console of the casper script:
CasperJS 包括ClientUtils,可以从远程页面使用它轻松登录到 casper 脚本的控制台:
__utils__.echo('This message is logged from the remote page to the CasperJS console');
回答by c24w
Building on @odigity's answer, this makes casperjs die with a more familiar error/stacktrace:
以@odigity 的回答为基础,这使得 casperjs 因更熟悉的错误/堆栈跟踪而死亡:
var util = require('util');
casper.on('page.error', function exitWithError(msg, stack) {
stack = stack.reduce(function (accum, frame) {
return accum + util.format('\tat %s (%s:%d)\n',
frame.function || '<anonymous>',
frame.file,
frame.line
);
}, '');
this.die(['Client-side error', msg, stack].join('\n'), 1);
});