1

I'm new to casperjs and playing around with it, but I can't get its evaluate() functionality to work.

This is my example

var casper = require('casper').create();

casper.echo('started...');

casper.start('http://www.google.de/');

casper.then(function() {
    this.echo(this.getTitle());
});

casper.then(function() {
    this.evaluate(function() {
        this.echo('test');
    });
});

casper.run();

I'm executing it with casperjs sample.js

After started... and Google nothing happens in console output. The closure function given in the evaluate method is not executed.

I don't even get further informations by console with --verbose.

What am I doing wrong?

1 Answer 1

7

Inside of the casper.evaluate callback is the page context. Everything in it executes directly on the page and it is sandboxed. this refers to the window object inside this callback. I doubt that google has added a window.echo function. So you will not see something in the console. this.echo or casper.echo are only usable outside of the page context.

To actually see console messages from the page context you need to register to the remote.message event:

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

and write something to the console:

this.evaluate(function() {
    console.log('test');
});

If you would have registered to the page.error event:

casper.on("page.error", function(pageErr){
    this.echo("page.err: " + JSON.stringify(pageErr));
});

you would have seen, that window.echo cannot be called because it is undefined. Calling it, will result in a TypeError, which stops execution of the evaluate() callback, which then gives you null as the result of the evaluate() execution.

For more info on evaluate see my answer here.

Note: It is not a good idea to try to write your first scripts on google, because you will run into multiple problems. Google sniffs the user-agent and will give you a different site depending on it. Also the viewport size will be taken into account. I would suggest you start with example.org and then stackoverflow.com, because both behave rather well.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.