使用WebBrowser.Document.InvokeScript调用javascript对象方法

在我的WinForms应用程序中,我需要从我的WebBrowser控件调用javascript函数。 我使用了Document.InvokeScript,它与单独的function完美配合,例如

Document.InvokeScript("function"). 

但是当我想调用javascript对象方法时,例如

 Document.InvokeScript("obj.method") 

它不起作用。 有没有办法让它发挥作用? 或者解决这个问题的方法不同? 无需改变javascript代码中的任何内容!

提前致谢 :)

文档中的示例不包括括号。

 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,Object []),则可以传递参数。

编辑

看起来你不是唯一有这个问题的人: HtmlDocument.InvokeScript – 调用一个对象的方法 。 您可以像该链接的海报所示制作“代理function”。 基本上你有一个调用你的对象function的函数。 这不是一个理想的解决方案,但它肯定会奏效。 我会继续看看这是否可行。

关于同一问题的另一篇文章: 使用WebBrowser.Document.InvokeScript()搞乱外国JavaScript 。 C.Groß在CodeProject上提出的有趣解决方案:

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

您可以在HtmlDocument上创建一个扩展方法并调用它来运行您的函数,只使用这个新函数,您将包括括号,参数,您传入的字符串中的整个九码(因为它只是传递给了一个eval) 。

看起来HtmlDocument不支持在现有对象上调用方法。 只有全球function。 🙁

遗憾的是,您无法使用WebBrowser.Document.InvokeScript调用开箱即用的对象方法。

解决方案是在JavaScript端提供一个全局function,可以重定向您的呼叫。 以最简单的forms,这将是:

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

在您的.NET代码中,您将使用如下:

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

正如您所提到的,您无法对现有的JavaScript代码进行任何更改,您必须在某些方法中注入上述JavaScript方法。 幸运的是,WebBrowser控件也可以通过调用eval()方法为您完成:

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

有关更强大和完整的实现,请参阅我编写的WebBrowser工具和解释ScriptingBridge的文章,该文章专门用于解决您描述的问题。

  webBrowser.Document.InvokeScript("execScript", new object[] { "this.alert(123)", "JavaScript" }) 

因为你应该是这样的

  webBrowser.Document.InvokeScript("execScript", new object[] { "obj.method()", "JavaScript" })