Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PhantomJs passing parameters to inner function page.evaluate [duplicate]

Using PhantomJs, I'm trying to create a function which takes a select tag id and the String of an option's text content, and returns the value of the associated option. I'm unsure of how to pass the parameters from the outermost function to the function passed to page.evaluate. Below is what I've tried, but the variables come out as undefined inside page.evaluate.

function getOptionValue(selectID, name)
{
    console.log("Select ID: " + selectID);
    console.log("name: " + name);

    return tempPage.evaluate(function(selectID, name) {
        console.log("SELECT ID: " + selectID);
        var elem = document.getElementById(selectID);
        console.log("elem type: " + elem.type);
        for(var i = 0; i < elem.length; i++)
        {
            if(elem.options[i].text.toLowerCase() === name.toLowerCase())
            {
                return elem.options[i].value;
            }
        }

        return "nothing";
    });
}
like image 357
Matthew Allbee Avatar asked Sep 11 '25 18:09

Matthew Allbee


1 Answers

PhantomJS has good documentation, including page.evaluate function, please be sure to always check it first.

Your function can be fixed this way (removed console.log for brevity):

function getOptionValue(selectID, name)
{
    return tempPage.evaluate(function(selectID, name) {

        var elem = document.getElementById(selectID);
        for(var i = 0; i < elem.length; i++)
        {
            if(elem.options[i].text.toLowerCase() === name.toLowerCase())
            {
                return elem.options[i].value;
            }
        }

        return "nothing";
    }, selectID, name); // <-- parameters are passed to page.evaluate after the function 
}
like image 116
Vaviloff Avatar answered Sep 13 '25 08:09

Vaviloff