Message does not appear when called from evaluate method

孤者浪人 提交于 2019-12-03 22:55:41

问题


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:


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.



来源:https://stackoverflow.com/questions/25135598/message-does-not-appear-when-called-from-evaluate-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!