Calling javascript object method using WebBrowser.Document.InvokeScript

前端 未结 3 1043
天命终不由人
天命终不由人 2020-12-09 21:05

In my WinForms application I need to call javascript function from my WebBrowser control. I used Document.InvokeScript and it works perfect with functions alone e.g

3条回答
  •  执笔经年
    2020-12-09 21:38

    Unfortunately you can't call object methods out of the box using WebBrowser.Document.InvokeScript.

    The solution is to provide a global function on the JavaScript side which can redirect your call. In the most simplistic form this would look like:

    function invoke(method, args) {
    
        // The root context is assumed to be the window object. The last part of the method parameter is the actual function name.
        var context = window;
        var namespace = method.split('.');
        var func = namespace.pop();
    
        // Resolve the context
        for (var i = 0; i < namespace.length; i++) {
            context = context[namespace[i]];
        }
    
        // Invoke the target function.
        result = context[func].apply(context, args);
    }
    

    In your .NET code you would use this as follows:

    var parameters = new object[] { "obj.method", yourArgument };
    var resultJson = WebBrowser.Document.InvokeScript("invoke", parameters);
    

    As you mention that you cannot change anything to your existing JavaScript code, you'll have to inject the above JavaScript method in some how. Fortunately the WebBrowser control can also do for you by calling the eval() method:

    WebBrowser.Document.InvokeScript("eval", javaScriptString);
    

    For a more robust and complete implementation see the WebBrowser tools I wrote and the article explaining the ScriptingBridge which specifically aims to solve the problem you describe.

提交回复
热议问题