Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 921
Alex Avatar asked Sep 26 '12 23:09

Alex


1 Answers

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));
like image 114
JimEvans Avatar answered Oct 10 '22 02:10

JimEvans