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

后端 未结 2 1868
[愿得一人]
[愿得一人] 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) })
    
    0 讨论(0)
  • 2020-12-05 21:40

    As @Frogmouth noted here already you can pass callback function name to the LongRunningProcedure:

    function onComplete( result )
    {
        alert( result );
    }
    
    function start()
    {
        window.external.LongRunningProcess( 'data', 'onComplete' );
    }
    

    and when LongRunningProcedure completes use .InvokeScript as the following:

        public void LongRunningProcess(string data, string callbackFunctionName)
        {
            // do work, call the callback
    
            string codeStrig = string.Format("{0}('{1}')", callbackFunctionName, "{{ Your result value here}}");
            webBrowser1.Document.InvokeScript("eval", new [] { codeStrig});  
        }
    
    0 讨论(0)
提交回复
热议问题