调用使用WebBrowser.Document.InvokeScript JavaScript对象方法对象、方法、Document、WebBrowser

2023-09-03 02:05:25 作者:刘老汉*

在我的WinForms应用程序,我需要从我的WebBrowser控件调用javascript函数。我用Document.InvokeScript,它可以完美兼容功能,例如单独

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

Document.InvokeScript("function").

但是,当我想调用JavaScript对象的方法,如:

But when i want to call javascript object method e.g.

Document.InvokeScript("obj.method")

这是行不通的。有没有一种方法,使其工作?或不同的解决这个问题? 没有在JavaScript中code更改任何东西!

it doesn't work. Is there a way to make it work? Or different solution to this problem? Without changing anything in the javascript code!

在此先感谢:)

推荐答案

在文档中的例子不包括括号。

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");
    }
}

尝试

Document.InvokeMethod("obj.method");

请注意,如果你使用,你可以传递参数 HtmlDocument.InvokeScript方法(String,对象[])。

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

看起来,你是不是唯一一个与此问题: HtmlDocument.InvokeScript - 调用对象的方法。你可以做一个代理功能之类的链接的海报建议。基本上,你有一个函数调用的对象的功能。这不是一个理想的解决方案,但它肯定会工作。我将继续寻找,看是否是可能的。

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.

在同一问题的另一个帖子:Using WebBrowser.Document.InvokeScript()弄乱与国外的JavaScript 。在$ C $的CProject提出C.格罗斯有趣的解决方案:

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();
}

您可以做出对的HTMLDocument扩展方法,并调用运行的功能,只有使用这种新功能,您将包括括号,参数,整个九码传递的(因为它只是沿着传递的字符串一个eval)。

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).

看起来的HTMLDocument没有调用现有对象的方法支持。只有全局函数。 :(

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