Search code examples
javascriptcasperjs

How to pass a parameter / variable to casperjs evaluate function


I can't get casper evaluate function to work when passing a variable. The code below returns null when utils.dump(locations);

var selectors = {

    locationSelector: ".job-location",
    nextPage: '.next'
}

locations = this.evaluate(function (selector) {
            var locs = document.querySelectorAll(selector);
            locs = Array.prototype.map.call(locs, function (loc) {
                return loc.innerText;
            }, { selector: selectors.locationSelector });
            return locs;
        })

The code below with the selector value hard coded is working...

locations = this.evaluate(function () {
            var locs = document.querySelectorAll('.job-location');
            locs = Array.prototype.map.call(locs, function (loc) {
                return loc.innerText;
            });
            return locs;
        })

Can anybody please point me in the right direction. I've read numerous posts and nothing I've found seems to be working. I have many different scripts which use this evaluation, so I really need to be able to pass the variable in.

Thank you for any assistance in advance.


Solution

  • The syntax is casper.evaluate(callbacl, param1, param2 ...).

    You have to write this.evaluate(..., selector); with the right 'selector' variable. The function written in this.evaluate is stringified and sent to phantomjs, which unserialize it and execute it.

    That function cannot access the variables that you dont bind in the 'evaluate' method, because it's not executed in the same context.