Search code examples
javascriptbrowserphantomjscasperjs

casperjs can't find the id after set id


casperjs can't find the id after set id

casper.then(function () {
screenLog();
var id =  String("_newid_");
var arrow = this.evaluate(function () {
    var arrows = document.querySelectorAll('span.select2-selection__arrow');
    arrows[1].innerHTML = "aa";
    arrows[1].id = id;
    return arrows[1].innerHTML;
});
screenLog();
this.click("#"+id);
screenLog();});

and then error code : CasperError: Cannot dispatch mousedown event on nonexistent selector: #newid


Solution

  • Caspers evaluate method runs in separate environment(DOM environment) so the variables defined in casper environment are not accessible in browser environment. However you can pass the variable to browser environment by adding extra parameters to evaluate function.

    So for your case id is undefined, but you can pass it properly like this

    var id =  String("_newid_");
    var arrow = this.evaluate(function (id) {
        var arrows = document.querySelectorAll('span.select2-selection__arrow');
        arrows[1].innerHTML = "aa";
        arrows[1].id = id;
        return arrows[1].innerHTML;
    }, id);