如何在WebBrowser控件中注入Javascript

这里有关于Windows窗体的很棒的教程

如何在WebBrowser控件中注入Javascript?

我尝试过它,效果很好

但问题是在wpf应用程序中无法识别所使用的对象。 所以我要问的是wpf应用程序中下面函数的等价物。 谢谢。

HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0]; HtmlElement scriptEl = webBrowser1.Document.CreateElement("script"); IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement; string srJquery = File.ReadAllText("jquery.txt"); element.text = srJquery; head.AppendChild(scriptEl); 

上面的函数在Windows窗体应用程序c#4.0中完美地工作,但是在WPF应用程序中无法识别HtmlElement等已使用的对象。

这有用吗?

  private void WebBrowser_LoadCompleted (object sender, System.Windows.Navigation.NavigationEventArgs e) { var webBrowser = sender as WebBrowser; var document = webBrowser.Document as mshtml.HTMLDocument; var ahref = document.getElementsByTagName("A").Cast().First(); ahref.setAttribute( "onmouseenter", "javascript:alert('Hi');", 1); } 

您需要的是Microsoft.mshtml (.net API而不是MS office one)参考。

另请参阅此代码,以ObjectForScripting使用WebBrowser ObjectForScripting属性的WPF webbrowser控件,它可以帮助您注入javascript …

http://blogs.msdn.com/b/wpf/archive/2011/05/27/how-does-wpf-webbrowser-control-handle-window-external-notify.aspx

如果这有帮助,请告诉我。

我在网上找到的最佳答案来自http://clistax.com/question/qt/153748/st/4eb64b29180c4

我相信从c#在WebBrowser控件HTML文档中注入Javascript的最简单方法是调用“execStrip”方法,并将代码作为参数注入。

在此示例中,javascript代码在全局范围内注入并执行:

 var jsCode="alert('hello world from injected code');"; WebBrowser.Document.InvokeScript("execScript", new Object[] { jsCode, "JavaScript" }); 

如果要延迟执行,请注入函数并在以下情况后调用它们:

 var jsCode="function greet(msg){alert(msg);};"; WebBrowser.Document.InvokeScript("execScript", new Object[] { jsCode, "JavaScript" }); WebBrowser.Document.InvokeScript("greet",new object[] {"hello world"}); 

这适用于Windows窗体和WPF WebBrowser控件。

此解决方案不是跨浏览器,因为“execScript”仅在IE和Chrome中定义。 但问题是关于Microsoft WebBrowser控件和IE是唯一支持的。

我发现这有助于在wpf中讨论invokes脚本eqivilent,只是在html中执行脚本代码: http : //msdn.microsoft.com/en-us/library/cc452443.aspx