console.log doesn't work in CasperJS' evaluate with setTimeout

邮差的信 提交于 2019-11-26 13:57:23

问题


Why when I use console.log in evaluate, it works:

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

回答1:


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.

If you want to catch remote console.log calls, listen to the remote.message event:

casper.on('remote.message', function(msg) {
    this.echo('remote message caught: ' + msg);
})

Btw, documentation for events is pretty much exhaustive, as well as the one for evaluate.




回答2:


@NiKo's answer is critical.

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.

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



回答3:


CasperJS includes ClientUtils, which can be used from the remote page to easily log to the console of the casper script:

__utils__.echo('This message is logged from the remote page to the CasperJS console');



回答4:


Building on @odigity's answer, this makes casperjs die with a more familiar error/stacktrace:

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


来源:https://stackoverflow.com/questions/11864373/console-log-doesnt-work-in-casperjs-evaluate-with-settimeout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!