Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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!

share|improve this question
    
"object" should be written as "Object" –  Mik378 Sep 26 '12 at 23:49
3  
@Mik378 object is an alias for System.Object in C#, so that makes no difference. –  Joe Enos Sep 26 '12 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? –  Joe Enos Sep 26 '12 at 23:51
    
I read too quickly, I though that it was a Java code ;) –  Mik378 Sep 26 '12 at 23:51
    
@Mik378 Yep, drives me nuts when I try to write java, and it yells at me when I type string. –  Joe Enos Sep 26 '12 at 23:51

1 Answer 1

up vote 3 down vote accepted

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));
share|improve this answer
1  
Works a treat. Nice to get a lightning reply from a Selenium author, that's what Stack is all about :D –  Alex Sep 27 '12 at 0:16

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.