Question

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

Was it helpful?

Solution

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.

OTHER TIPS

I really got it to work now myself with the IReflect interface! :-)

You need to implement the methods GetProperties and InvokeMember yourself: in GetProperties you need to make sure there is a property returned with the name "length" and a property for "0" till the length-1 of the array. In InvokeMember you just check then which method JavaScript wants to call and return the correct result.

The biggest problem I had was that the class PropertyInfo is abstract - so I can't create a new object out of it. So I needed to derive an own class from it and use that to return custom property names.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top