Search code examples
javascriptcasperjs

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

Solution

  • 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.