本文实例总结了C#的WEBBROWSER与JS交互的方法。分享给大家供大家参考。具体实现方法如下:
一、实现WebBrowser内部跳转,阻止默认打开IE
1、引用封装好的WebBrowserLinkSelf.dll实现
复制代码代码如下:
public partial class MainWindow : Window
{
private WebBrowser webBrowser = new WebBrowser();
public MainWindow()
{
InitializeComponent();
this.webBrowser.LoadCompleted += new LoadCompletedEventHandler(webBrowser_LoadCompleted);
//使webbrowser寄宿于Label上,实现webborwser内部跳转,不用IE打开
Label lb = new Label { Content = webBrowser };
WebBrowserHelper webBrowserHelper = new WebBrowserHelper(webBrowser);
HelperRegistery.SetHelperInstance(lb, webBrowserHelper);
webBrowserHelper.NewWindow += WebBrowserOnNewWindow;
this.lbBrowserHost.Content = lb;
// this.webBrowser.Navigate(new Uri("http://www.baidu.com", UriKind.RelativeOrAbsolute));
}
private void WebBrowserOnNewWindow(object sender, CancelEventArgs e)
{
dynamic browser = sender;
dynamic activeElement = browser.Document.activeElement;
var link = activeElement.ToString();
this.webBrowser.Navigate(new Uri(link, UriKind.RelativeOrAbsolute));
e.Cancel = true;
}
}
2、引用com:Microsoft Internet Controls实现(参考MSDN:http://msdn.microsoft.com/en-us/library/system.windows.controls.webbrowser.aspx public partial class MainWindow : Window
复制代码代码如下:
<em id="__mceDel"> {
public MainWindow()
{
InitializeComponent();
this.webBrowser1.Navigate(new Uri("http://www.baidu.com", UriKind.RelativeOrAbsolute));
this.webBrowser1.LoadCompleted += new LoadCompletedEventHandler(webBrowser1_LoadCompleted);
}
private IServiceProvider serviceProvider;
void webBrowser1_LoadCompleted(object sender, NavigationEventArgs e)
{
if (this.serviceProvider == null)
{
serviceProvider = (IServiceProvider)webBrowser1.Document;
if (serviceProvider != null)
{
Guid serviceGuid = new Guid("0002DF05-0000-0000-C000-000000000046");
Guid iid = typeof(SHDocVw.WebBrowser).GUID;
var webBrowserPtr = (SHDocVw.WebBrowser)serviceProvider
.QueryService(ref serviceGuid, ref iid);
if (webBrowserPtr != null)
{
webBrowserPtr.NewWindow2 += webBrowser1_NewWindow2;
}
}
}
}
private void webBrowser1_NewWindow2(ref object ppDisp, ref bool Cancel)
{
dynamic browser = this.webBrowser1;
dynamic activeElement = browser.Document.activeElement;
var link = activeElement.ToString();
this.webBrowser1.Navigate(new Uri(link, UriKind.RelativeOrAbsolute));
Cancel = true;
}
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("6d5140c1-7436-11ce-8034-00aa006009fa")]
internal interface IServiceProvider
{
[return: MarshalAs(UnmanagedType.IUnknown)]
object QueryService(ref Guid guidService, ref Guid riid);
}
}
</em>
二、WebBrowser与JS的交互
1、与页面标签的交互
复制代码代码如下:
//引用Microsoft.mshtml
//1、添加一个html标签到id为lg的div中
HTMLDocument doc = (HTMLDocument)this.webBrowser.Document;
IHTMLElement lbelem = doc.createElement("button");
lbelem.innerText = "test";
lbelem.style.background = "red";
IHTMLDOMNode node = doc.getElementById("lg") as IHTMLDOMNode;
node.appendChild(lbelem as IHTMLDOMNode);
//2、设置id为su的标签value值和style
//2.1 使用setAttribute
HTMLDocument doc = (HTMLDocument)this.webBrowser.Document;
IHTMLElement search = doc.getElementById("su");
IHTMLDOMAttribute att = search.getAttribute("value") as IHTMLDOMAttribute;
search.setAttribute("value", "百度一下");
//search.click();
search.style.display = "none";
//2.2 使用outerHtml
search.outerHTML = "<input id=/"su/" value=/"百度一下/" class=/"bg s_btn/" type=/"submit/" onclick=/"alert('百度一下');/" />";
//2.3 使用IHTMLDOMAttribute
IHTMLAttributeCollection attributes = (search as IHTMLDOMNode).attributes as IHTMLAttributeCollection;
foreach (IHTMLDOMAttribute attr in attributes)
{
if (attr.nodeName == "value")
{
attr.nodeValue = "百度一下";
}
}
//3、替换应用了类样式mnav的a标签
HTMLDocument doc = (HTMLDocument)this.webBrowser.Document;
IHTMLElementCollection collect = doc.getElementsByTagName("a");
foreach (IHTMLElement elem in collect)
{
if (!(elem is IHTMLUnknownElement) && elem.className != null)
{
if (elem.className.Equals("mnav", StringComparison.OrdinalIgnoreCase))
{
elem.outerHTML = "<a href='#' style="border-left-color: rgb(0, 153, 204); border-left-width: 1px; border-left-style: solid; padding: 0px 3px; margin: 3px auto 0px; width: 640px; background-color: rgb(242, 246, 251); clear: both; border-top-color: rgb(0, 153, 204); border-top-width: 1px; border-top-style: solid; border-right-color: rgb(0, 153, 204); border-right-width: 1px; border-right-style: solid;"> 复制代码代码如下:
public MainWindow()
{
InitializeComponent();
this.webBrowser.ObjectForScripting = new ScriptEvent();
this.webBrowser.NavigateToString(@"<html><head><title>Test</title></head><body><input type=""button"" value=""点击"" onclick=""window.external.ShowMessage('百度一下');"" /></body></html>");
}
[System.Runtime.InteropServices.ComVisible(true)]
public class ScriptEvent
{
//供JS调用
public void ShowMessage(string message)
{
MessageBox.Show(message);
}
}
希望本文所述对大家的C#程序设计有所帮助。