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() {

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

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>',
    }, '');
    this.die(['Client-side error', msg, stack].join('\n'), 1);


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.