Search code examples
javascriptcasperjs

Passing parameters to function in CasperJS's evaluate


How can I pass a parameter to a function within CasperJS's evaluate?

    //Should be logged in at this point
    casper.then(function() {
        var counter = 0;
        var cap = 500;

        this.evaluate(function(counter) {
            var children = $('.companies-using-service').children();

            while (counter < children.length) {
                child = children[counter];
                console.log($(child).find('a').attr('data-hint'));
                counter++;
            }
        }, counter);
    });
};

var scrapeClients = function(counter) {
    var children = $('.companies-using-service').children();

    while (counter < children.length) {
        child = children[counter];
        console.log($(child).find('a').attr('data-hint'));
        counter++;
    }
}

Above, I am able to pass parameters in using an unamed function. However, I wish to pass in the function scrapeClients to the evaluate function. In that case, I tried the following this.evaluate(scrapeClients(counter), counter). However, this does not work and the error says that it could not find $ variable.


Solution

  • Functions are first-class citizen in JavaScript. You can treat them in the same way as variables. You can pass them around. This means that you don't want

    this.evaluate(scrapeClients(counter), counter)
    

    but rather

    this.evaluate(scrapeClients, counter)
    

    In the first case, you're actually calling the function directly. Since the function uses some page properties that are only available inside of casper.evaluate, this will throw an error and stop the script.