.Net Winform(C#) WebBrowser + Javascript 随意说
使用Winform WebBrowser控件对访问页面执行、改写、添加Javascript代码,可以解决许多问题,实现你想要的效果。
可以通过引用Microsoft.mshtml,实现对Javascript的操作,代码如下:
mshtml.IHTMLDocument2 doc = webBrowser1.Document.DomDocument as mshtml.IHTMLDocument2;
mshtml.IHTMLWindow2 win = doc.parentWindow as mshtml.IHTMLWindow2;
win.execScript(@"alert('hello webbrowser')", "javascript");
其实还有一种更好的、无需引用Microsoft.mshtml的实现方式:
HtmlElement ele = webBrowser1.Document.CreateElement("script");
ele.SetAttribute("type", "text/javascript");
ele.SetAttribute("text", "alert('hello webbrowser')");
webBrowser1.Document.Body.AppendChild(ele);
这种使用.Net框架本身所提供的对象,相比引用框架外的COM,好处是显而易见的,这将更方便于安装部署至客户机上。

