console.log在CasperJS'使用setTimeout进行评估时不起作用

Rus*_*tem 31 javascript casperjs

为什么当我使用console.logevaluate,它的工作原理:

casper.then(function() {
  this.evaluate( function() {
    console.log('hello'); 
  });
});
Run Code Online (Sandbox Code Playgroud)

但这不起作用:

casper.then(function() {
  this.evaluate( function() {
    setTimeout( function() {console.log('hello');}, 1000);
  });
});
Run Code Online (Sandbox Code Playgroud)

NiK*_*iKo 72

因为你正在混合casperjs和远程页面环境.该evaluate函数将在远程页面env中执行代码,因此console.log调用不会输出任何内容.

如果您想捕获远程 console.log呼叫,请收听该remote.message事件:

casper.on('remote.message', function(msg) {
    this.echo('remote message caught: ' + msg);
})
Run Code Online (Sandbox Code Playgroud)

顺便说一句,事件的文档非常详尽,以及评估的文档.


odi*_*ity 20

@ NiKo的答案很关键.

我还建议添加以下内容,因为如果出现错误,您甚至可能无法打印出一个console.log()消息,而最终会沉默.

casper.on( 'page.error', function (msg, trace) {
    this.echo( 'Error: ' + msg, 'ERROR' );
});
Run Code Online (Sandbox Code Playgroud)


piu*_*ius 11

CasperJS包含ClientUtils,可以从远程页面使用它轻松登录到casper脚本的控制台:

__utils__.echo('This message is logged from the remote page to the CasperJS console');
Run Code Online (Sandbox Code Playgroud)


c24*_*24w 5

在@ 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);
});
Run Code Online (Sandbox Code Playgroud)