MarkusBernhardt / robotframework-selenium2library-java

Java port of the Selenium 2 (WebDriver) Python library for Robot Framework
Apache License 2.0
46 stars 51 forks source link

Add the possibility to pass arguments to "Execute Javascript" and "Execute Async Javascript" #60

Open Marco85Li opened 9 years ago

Marco85Li commented 9 years ago

Hi,

currently it's seem not possible to pass not primitive arguments to javascript code. Example:

in .tsv file:

${Name} =   Set Variable    MyName
${Surname} =    Set Variable    MySurname
${Person} = Create List ${Name} ${Surname}

Execute Javascript  showPerson('Mr.', ${Person}); # This is wrong for sure

And in the html file opened in a browser the Javascript function

function showAlert(title, person) {
      alert('You are ' + title + ' ' + person[0] + ' ' + person[1] );
}

Obviously in this case we can change the array "person" with two distinct parameters and solve the problem, but in case of complex objects it is not possible.

A possible enhancement could be an additional keyword

Execute Javascript With Arguments   code *args

Where "code" is just a single line of code (previously joined at tsv level if needed) and args is variadic.

The implementation could be very similar:

@RobotKeyword
@ArgumentNames({ "js", "*args" })
public Object executeJavascriptWithArguments(String js, Object ... args) {
        String.format("Executing JavaScript:\n%s", js); //TODO log args
        JavascriptExecutor je = (JavascriptExecutor) browserManagement.getCurrentWebDriver();
        return je.executeScript(js, args);
}

Equivalent implementation for the Asynchronous version of the keyword.

What do you think?

Tattoo commented 9 years ago

You can already achieve this by crafting the javascript you want to execute correctly:

Execute Javascript    showPerson('Mr.', ['${Name}', '${Surname}']);