Message does not appear when called from evaluate method

烈酒焚心 提交于 2019-12-01 01:21:25
Artjom B.

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.

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