Calling javascript object method using WebBrowser.Document.InvokeScript

前端 未结 3 1060
天命终不由人
天命终不由人 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:27

    The example in the documentation does NOT include the parenthesis.

    private void InvokeScript()
    {
        if (webBrowser1.Document != null)
        {
            HtmlDocument doc = webBrowser1.Document;
            String str = doc.InvokeScript("test").ToString() ;
            Object jscriptObj = doc.InvokeScript("testJScriptObject");
            Object domOb = doc.InvokeScript("testElement");
        }
    }
    

    Try

    Document.InvokeMethod("obj.method");
    

    Note that you can pass arguments if you use HtmlDocument.InvokeScript Method (String, Object[]).

    Edit

    Looks like you aren't the only one with this issue: HtmlDocument.InvokeScript - Calling a method of an object . You can make a "Proxy function" like the poster of that link suggests. Basically you have a function that invokes your object's function. It's not an ideal solution, but it'll definitely work. I'll continue looking to see if this is possible.

    Another post on same issue: Using WebBrowser.Document.InvokeScript() to mess around with foreign JavaScript . Interesting solution proposed by C. Groß on CodeProject:

    private string sendJS(string JScript) {
        object[] args = {JScript};
        return webBrowser1.Document.InvokeScript("eval",args).ToString();
    }
    

    You could make that an extension method on HtmlDocument and call that to run your function, only using this new function you WOULD include parenthesis, arguments, the whole nine yards in the string you pass in (since it is just passed along to an eval).

    Looks like HtmlDocument does not have support for calling methods on existing objects. Only global functions. :(

提交回复
热议问题