views:

69

answers:

1

Given the following C# code:

    public object CallJavaScriptFunction(string functionName, params object[] args)
    {
        object script = Document.Script;
        var result = script.GetType().InvokeMember(functionName, BindingFlags.InvokeMethod, null, script, args);

        return result;
    }

And the following client-side JavaScript block:

function someFunction() {
    alert('This is only a test!');
}

var someObj = {
    someMethod: function() {
        alert('This is another test!');
    }
}

The following server-side block executes successfully:

CallJavaScriptFunction("someFunction");

But this will throw a DISP_E_UNKNOWNNAME:

CallJavaScriptFunction("someOBj.someMethod");

Obviously I'm doing something wrong here - probably there is another way of calling InvokeMember on JavaScript instance methods, but I was not able to find out how.

Any thoughts? Any help will be appreciated.

+1  A: 

You need to invoke the someObj property, then invoke the someMethod method on the value of the property

SLaks
I've never used .NET, and all the web app development i've dont is on PHP. Naturally, calling js code from the server (and indeed being able to do so) seems blasphemous to me. Can you please cite a couple of use cases where this might be required? Thanks.
Here Be Wolves
@Here: He's apparently automating a server-side instance of the WebBrowser control displaying a (presumably) different page. I hope he knows what he's doing; that's generally a bad (and slow) idea.
SLaks
@Here: This will be used for system tests automation - think of something like Selenium tests (http://seleniumhq.org/). So I guess I've not commited any mortal sin here... :-)
rsenna
@SLaks: Sounds you're right. I'm gonna test you're solution.
rsenna
@SLaks: Oh he is using WebBrowser. Just now I really feel confused when I saw his code. Now it's quite clear. haha~
Danny Chen
@rsenna: If you're using the WinForms `WebBrowser` object, you should try the document's `InvokeScript` method instead.
SLaks
Okay.. Me Be Happy.. :)
Here Be Wolves
@SLaks, @Danny: Just for the sake of argument, I am NOT using a WebBrowser object. All these calls are made to a real (IE) browser instance.
rsenna
@rsenna: It's still a bad idea.
SLaks
@SLaks: It's a bad idea to create a tool for UI tests and continuous integration? Weird. Anyway, it's my employer's idea, not mine... ;-)
rsenna
I meant that automating IE on a server is a bad idea. (I misunderstood)
SLaks