Felix Feliciant Felix Feliciant - 4 months ago 19
PHP Question

Selenium 2 phpunit get value from injected javascript code

I am using Selenium2TestCaseTest, which can be found here
and I am trying to get the value of a jquery slider, after searching here I have found this solution

$this->execute(
array(
'script' => "$('#Slider_id').slider('option', 'value', 505);",
'args' => array()
)
);


but it only allows me to change the value of the slider, then I tried to get it's value with these commands:

$this->execute(
array(
'script' => "$('#Slider_id').slider('option', 'value');",
'args' => array()
)
);


and this:

$this->execute(
array(
'script' => "$('#Slider_id').slider('value');",
'args' => array()
)
);


and it does not return anything (NULL), can anyone help me with this please?

Answer

In order to get the value returned by a code you injected to the browser using selenium you need to add return before the code you run.
This is relevant to EVERY javascript code you run using selenium, and not specifically to jQuery ui slider.

$val = $this->execute([
    'script' => "return $('#Slider_id').slider('option', 'value');"
    'args' => []
]);

Much simpler examples:

$val1 = $this->execute([
    'script' => "return 1;"
    'args' => []
]);

$val2 = $this->execute([
    'script' => "return Math.max(10, 15);"
    'args' => []
]);

$val3 = $this->execute([
    'script' => "return function(){return 2}();"
    'args' => []
]);
Comments