How to return an array from javascript? (ExecuteScript)

Although returning a string is a cake, I just can't figure out how to return an array, this is an example that doesn't 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>; 

Error: The object reference is not installed in the object instance.

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

+4
source share
1 answer

When you return an array from JavaScript, .NET bindings return ReadOnlyCollection<object> , not List<object> . The reason for this is because you cannot expect the contents of the returned collection to change and update it in JavaScript on the page. The following is an example taken from a WebDriver project, native .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)); 
+9
source

Source: https://habr.com/ru/post/1436488/


All Articles