Using WebBrowser on a Form and calling into C# from Javascript with window.external. Passing in a Javascript array of classes in the function:
var x = [];
x.push(classa);
x.push(classa);
window.external.CSharpFunction(x);
I can successfully get x.length in C# with:
int length=(int)x.GetType().InvokeMember("length", BindingFlags.GetProperty, null, x, null);
My question is how do I get x[0] and x[1]? I've tried
x.GetType().InvokeMember(string.Empty, BindingFlags.GetProperty, null, x, new object[1]{1});
and
x.GetType().InvokeMember(string.Empty, BindingFlags.InvokeMethod | BindingFlags.Default, null, x, new object[1]{0});
both of which fire off errors within the WebBrowser control.
Thanks
Using WebBrowser on a Form and calling into C# from Javascript with window.external. Passing in a Javascript array of classes in the function:
var x = [];
x.push(classa);
x.push(classa);
window.external.CSharpFunction(x);
I can successfully get x.length in C# with:
int length=(int)x.GetType().InvokeMember("length", BindingFlags.GetProperty, null, x, null);
My question is how do I get x[0] and x[1]? I've tried
x.GetType().InvokeMember(string.Empty, BindingFlags.GetProperty, null, x, new object[1]{1});
and
x.GetType().InvokeMember(string.Empty, BindingFlags.InvokeMethod | BindingFlags.Default, null, x, new object[1]{0});
both of which fire off errors within the WebBrowser control.
Thanks
Share Improve this question edited Jun 5, 2012 at 19:41 L.B 116k20 gold badges187 silver badges229 bronze badges asked Jun 5, 2012 at 19:35 Jamie MuellerJamie Mueller 931 silver badge3 bronze badges 2- Try to invoke the "0" member? (Just as with the "length" member.) – user166390 Commented Jun 5, 2012 at 19:39
- Nope: "0" also causes an error. – Jamie Mueller Commented Jun 6, 2012 at 11:32
1 Answer
Reset to default 5Please see this SO question:
Accessing properties of javascript objects using type dynamic in C# 4
I've also tried to retrieve values from properties on objects in the array without success. Retrieving simple values in the array, such as strings and integers is easy, but have had no luck with plex objects.
Your best bet (IMO) is to implement a similar solution as the one in the above SO question. Instead of passing the array directly, build a Javascript method that can be invoked from C# that will return the object in the array at the specified index. Like so:
C#
public void CSharpFunction(dynamic length)
{
for (int i = 0; i < length; i++)
{
dynamic obj = webBrowser1.Document.InvokeScript("getObj", new object[] { i });
string val = obj.MyClassValue;
}
}
HTML / JavaScript
<script type="text/javascript">
var x = [];
x.push({MyClassValue: "Hello"});
x.push({MyClassValue: "People"});
function test() {
window.external.CSharpFunction(x.length);
}
function getObj(i) {
return x[i];
}
</script>
<button onclick="test();" />