Alex
Alex

Reputation: 307

How to return an array from javascript? (ExecuteScript)

Although returning a string is cake, I just can't figure out how to return an array, this is an example that does not work (myURLs is a global array variable):

       List<object> list = ((IJavaScriptExecutor)driver).ExecuteScript(
        "window.myURLs = ['aa']; window.myURLs.push('bb'); return window.myURLs" 
        ) as List<object>;

The error is: Object reference not set to an instance of an object.

If anyone has an example of returning an array I would love to see it!

Upvotes: 6

Views: 4456

Answers (1)

JimEvans
JimEvans

Reputation: 27496

When returning an array from JavaScript, the .NET bindings return a ReadOnlyCollection<object>, not a List<object>. The reason for this is that you cannot expect to change the contents of the returned collection and have them updated in the JavaScript on the page. The following is an example taken from the WebDriver project's own .NET integration tests.

List<object> expectedResult = new List<object>();
expectedResult.Add("zero");
expectedResult.Add("one");
expectedResult.Add("two");
object result = ExecuteScript("return ['zero', 'one', 'two'];");
Assert.IsTrue(result is ReadOnlyCollection<object>, "result was: " + result + " (" + result.GetType().Name + ")");
ReadOnlyCollection<object> list = (ReadOnlyCollection<object>)result;
Assert.IsTrue(CompareLists(expectedResult.AsReadOnly(), list));

Upvotes: 15

Related Questions