I'm trying to access an array from C# in Javascript.
That's the JavaScript code:
var testArray = window.external.testfunction();
for(var i = 0; i < testArray.length; i++) {
alert(testArray[i]);
}
I tested it with following C# object assigned to the ObjectForScripting property:
[ComVisible(true)]
public class TestObject
{
public string[] testfunction()
{
var test = new string[1];
test[0] = "test";
return test;
}
}
Already when trying to access testArray.length
it throws an JavaScript error saying "function expected".
So how can I return an array back to the JavaScript code?
The JavaScript code is fix (I cannot modify it). So the function will be called with window.external.testfunction()
and as return value the JavaScript code expects an array.
How can I accomplish that from the C# side?
Best regards and thank you for any ideas on that
Andreas
I don't think that this works, because then JavaScript probably will not be able to access the array elements by using testArray[i], does it?
The object I mentioned in the comment would be the easiest way, but you would not be able to access its elements as testArray[i]
from JavaScript.
The hard way would be implement a class in C# which simulates JavaScript array object (so it is exposed to JavaScript as COM IDispatchEx
object and is accessible as testArray[i]
). Such C# class would need to implement IReflect
and IExpando
managed interfaces. If you want to go this route, I posted some more details here:
Yet another way of doing this. Despite you cannot modify the page's existing JavaScript, you still can inject some new JavaScript code, and do with it whatever you want.