6

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!

6
  • "object" should be written as "Object" Commented Sep 26, 2012 at 23:49
  • 3
    @Mik378 object is an alias for System.Object in C#, so that makes no difference. Commented Sep 26, 2012 at 23:50
  • If you let it return that array as a string, what would it contain? For example, does it give you the string "['aa','bb']" or something else, or nothing at all? Commented Sep 26, 2012 at 23:51
  • I read too quickly, I though that it was a Java code ;) Commented Sep 26, 2012 at 23:51
  • @Mik378 Yep, drives me nuts when I try to write java, and it yells at me when I type string. Commented Sep 26, 2012 at 23:51

1 Answer 1

15

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));
Sign up to request clarification or add additional context in comments.

1 Comment

Works a treat. Nice to get a lightning reply from a Selenium author, that's what Stack is all about :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.