Reputation: 1079
I need to get an empty array declared in a JavaScript script in a Java variable.
The JavaScript array is declared as so on a web page:
tc_vars["products"] = new Array();
(I only need the products
's array, not the tc_vars
one).
This is how I try to get this variable in Java :
Object[] value = (Object[]) js.executeScript("return tc_vars['products'];");
(Where js
is a JavascriptExecutor
associated with a Selenium WebDriver
).
I usually have no trouble using this method for getting Strings, but it seems it just won't work for an empty Array. Moreover, I don't have any error message, the WebDriver just crashes.
The executeScript
method returns an Object
variable. Casting it to a String
(when the JS variable is a String) works well, but I had no chance in casting this empty Array to String[]
or Object[]
.
Upvotes: 4
Views: 2430
Reputation: 13341
As I mentioned in my comment, you need to make sure you actually have access to tc_vars['products']
at the point which you want to test. E.g., manually open a browser, get to the point in the page where you would ask for that value using selenium, open devtools javascript console and check the value of tc_vars. If it's not available to you, it will not be available to the selenium webdriver.
Second thing is that for arrays, the selenium webdriver (at least the latest version: 2.42.2) returns ArrayList<Object>
and not Object[]
. so your cast should be:
ArrayList<Object> o = (ArrayList<Object>) js.executeScript("return tc_vars['products'];");
Upvotes: 2