Message does not appear when called from evaluate method

前端 未结 1 1050
清歌不尽
清歌不尽 2021-01-07 11:14

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 =          


        
相关标签:
1条回答
  • 2021-01-07 12:07

    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 讨论(0)
提交回复
热议问题