简体   繁体   中英

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

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

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 .

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM