How can I execute Javascript callback function from C# host application

后端 未结 2 1876
[愿得一人]
[愿得一人] 2020-12-05 20:47

I\'m creating an application in C# that hosts custom web pages for most of the GUI. As the host, I\'d like to provide a javascript API so that the embedded web pages can ac

2条回答
  •  再見小時候
    2020-12-05 21:31

    You can use Reflection for that:

    [ComVisible(true)]
    public class ScriptObject
    {
        public void LongRunningProcess(string data, object callback)
        {
            string result = String.Empty;
    
            // do work, call the callback
    
            callback.GetType().InvokeMember(
                name: "[DispID=0]",
                invokeAttr: BindingFlags.Instance | BindingFlags.InvokeMethod,
                binder: null,
                target: callback,
                args: new Object[] { result });
        }
    }
    

    You could also try dynamic approach. It'd be more elegant if it works, but I haven't verified it:

    [ComVisible(true)]
    public class ScriptObject
    {
        public void LongRunningProcess(string data, object callback)
        {
            string result = String.Empty;
    
            // do work, call the callback
    
            dynamic callbackFunc = callback;
            callbackFunc(result);
        }
    }
    

    [UPDATE] The dynamic method indeed works great, and probably is the easiest way of calling back JavaScript from C#, when you have a JavaScript function object. Both Reflection and dynamic allow to call an anonymous JavaScript function, as well. Example:

    C#:

    public void CallbackTest(object callback)
    {
        dynamic callbackFunc = callback;
        callbackFunc("Hello!");
    }
    

    JavaScript:

    window.external.CallbackTest(function(msg) { alert(msg) })
    

提交回复
热议问题