简体   繁体   中英

Javascript running into java : How to pass a java variable to a snippet javascript?

I want to pass a java variable to a snippet javascript from a java code. Please how could i perform that?

For example, From java i want to pass a java variable named 'index' to a snippet javascript like this

WebElement element = (WebElement) ((JavascriptExecutor)driver).executeScript("myJavascript.js") 

where myJavascript.js is this one:

var index=arguments[1]; return $('.title')[index];

I have been inspired by the site http://docs.seleniumhq.org/docs/03_webdriver.jsp#introducing-the-selenium-webdriver-api-by-example to write below code which does not work out:

int index=0;

for(int index = 0; index < counter; index++){

         WebElement element = (WebElement) ((JavascriptExecutor)driver).executeScript("var index=arguments[1]; return $('.title')[index];");
         System.out.println(element.getText());
    }

This above code works fine when i set values of the index to 0,1,2,....But I want to get it each time from the current value of loop 'for' from java.

Thanks.

If I get your question correctly, you need to do this:

WebElement element = (WebElement) ((JavascriptExecutor)driver).executeScript("var index=arguments[1]; return $('.title')["+index+"];");
System.out.println(element.getText());

Basically you need to make sure that "index" value is taken from loop variable - pay attention where the double quotes are in the above.

This should work:

for(int index = 0; index < counter; index++){
             WebElement element = (WebElement) ((JavascriptExecutor)driver).executeScript("return $('.title')[" + index + "];");
             System.out.println(element.getText());
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM