I'm using Selenium client driver 2.4.0. When running tests using the WebDriverBackedSelenium object, e.g.
final FirefoxDriver driver = new FirefoxDriver();
selenium = new WebDriverBackedSelenium(driver, baseUrl);
how do I inject a Javascript array into my tests that can retain scope across different pages? That is, I want to creat开发者_Go百科e a JS var "myArray" that I can access (using selenium.getEval) when I open "http://mydomain.com/page1.html" but I can then reference when I open a different page ("http://mydomain.com/page2.html") within the same Selenium test.
Thanks, - Dave
I don't think it is possible out of box.
Workaround should work - add to the page some library that can deserialize from JSON (e.g. Dojo), use it to load an array definition to some JavaScript variable and before leaving page get it back, storing it out of scope request.
But I must say you have a kind of strange request - what are trying to do ?
You can do it with casting. Execute JavaScript to return an array. The JS array must contain only one type, which must be primitive.
For example, execute a script which returns an array of Strings:
ArrayList<String> strings = (ArrayList<String>) js.executeScript(returnArrayOfStrings);
If you need an array of any other type, you can build it from those strings. For example, if you need an array of WebElements, design your JS to return locators, and then iterate through, finding elements and building a new array:
ArrayList<String> xpaths = (ArrayList<String>) js.executeScript(getLocators);
ArrayList<WebElement> elements = new ArrayList<WebElement>();
for (String xpath: xpaths){
element = driver.findElement(By.xpath(xpath));
elements.add(element);
}
You have the Array
in Java, so you can keep it in memory when your tests go to different pages and still reference the Java Array
,
The only catch is, if your JS array is changing on the client side, your Java Array
won't automatically update itself (the jsexecuter
only returns once per execution), but that's not a big deal - instead of referencing the Java Array
directly, you can access it via a getter which first executes the JS again to get a new Array
, which you can use to replace the previous one, or merge them etc, before returning the new/updated array to your test code.
精彩评论