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!
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With