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

后端 未结 4 677
Happy的楠姐
Happy的楠姐 2020-12-01 10:16

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

casper.then(function() {
  this.evaluate( function() {
    console.log(\'hello\')         


        
相关标签:
4条回答
  • 2020-12-01 10:54

    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');
    
    0 讨论(0)
  • 2020-12-01 11:14

    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.

    0 讨论(0)
  • 2020-12-01 11:14

    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);
    });
    
    0 讨论(0)
  • 2020-12-01 11:17

    @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' );
    });
    
    0 讨论(0)
提交回复
热议问题