C#的WEBBROWSER與JS交互小結(jié)
本文實例總結(jié)了C#的WEBBROWSER與JS交互的方法。分享給大家供大家參考。具體實現(xiàn)方法如下:
一、實現(xiàn)WebBrowser內(nèi)部跳轉(zhuǎn),阻止默認(rèn)打開IE
1、引用封裝好的WebBrowserLinkSelf.dll實現(xiàn)
{
private WebBrowser webBrowser = new WebBrowser();
public MainWindow()
{
InitializeComponent();
this.webBrowser.LoadCompleted += new LoadCompletedEventHandler(webBrowser_LoadCompleted);
//使webbrowser寄宿于Label上,實現(xiàn)webborwser內(nèi)部跳轉(zhuǎn),不用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實現(xiàn)(參考MSDN:http://msdn.microsoft.com/en-us/library/system.windows.controls.webbrowser.aspx public partial class MainWindow : Window
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、與頁面標(biāo)簽的交互
//1、添加一個html標(biāo)簽到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、設(shè)置id為su的標(biāo)簽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、替換應(yīng)用了類樣式mnav的a標(biāo)簽
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='#' title='替換標(biāo)簽' >替換</a>";
}
}
}
//4、刪除節(jié)點
HTMLDocument doc = (HTMLDocument)this.webBrowser.Document;
IHTMLElement search = doc.getElementById("su");
IHTMLDOMNode node = search as IHTMLDOMNode;
node.parentNode.removeChild(node);
//5、JS事件
//5.1 添加JS
HTMLDocument doc = (HTMLDocument)this.webBrowser.Document;
IHTMLElement search = doc.getElementById("su");
search.outerHTML = "<input id=\"su\" value=\"百度一下\" class=\"bg s_btn\" type=\"submit\" onclick=\"onClick();\" />";
IHTMLScriptElement scriptErrorSuppressed = (IHTMLScriptElement)doc.createElement("script");
scriptErrorSuppressed.type = "text/javascript";
scriptErrorSuppressed.text = "function onClick(){ alert('添加js'); }";
IHTMLElementCollection nodes = doc.getElementsByTagName("head");
foreach (IHTMLElement elem in nodes)
{
var head = (HTMLHeadElement)elem;
head.appendChild((IHTMLDOMNode)scriptErrorSuppressed);
}
//5.2 刪除JS
IHTMLElementCollection scripts = (IHTMLElementCollection)doc.getElementsByName("script");
foreach (IHTMLElement node in scripts)
{
if (!(node is IHTMLUnknownElement))
{
IHTMLScriptElement script = node as IHTMLScriptElement;
//刪除所有js文件引用
if (string.IsNullOrEmpty(script.text))
{
IHTMLDOMNode remove = script as IHTMLDOMNode;
remove.parentNode.removeChild(remove);
}
}
}
//6、write new html
mshtml.IHTMLDocument2 doc2 = this.webBrowser.Document as mshtml.IHTMLDocument2;
doc2.clear();
doc2.writeln("<HTML><BODY>write new html</BODY></HTML>");
2、數(shù)據(jù)交互
{
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調(diào)用
public void ShowMessage(string message)
{
MessageBox.Show(message);
}
}
希望本文所述對大家的C#程序設(shè)計有所幫助。
相關(guān)文章
詳解WPF如何使用WriteableBitmap提升Image性能
這篇文章主要為大家詳細(xì)介紹了WPF如何使用WriteableBitmap提升Image性能,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-01-01DevExpress之ChartControl創(chuàng)建Drill-Down樣式的Title實例
這篇文章主要介紹了DevExpress之ChartControl創(chuàng)建Drill-Down樣式的Title實現(xiàn)方法,以實例形式講述了創(chuàng)建Drill-Down樣式的Title原理與實現(xiàn)過程,需要的朋友可以參考下2014-10-10C#實現(xiàn)實體類與字符串互相轉(zhuǎn)換的方法
這篇文章主要介紹了C#實現(xiàn)實體類與字符串互相轉(zhuǎn)換的方法,涉及C#字符串及對象的相互轉(zhuǎn)換技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-08-08C#使用oledb讀取excel表格內(nèi)容到datatable的方法
這篇文章主要介紹了C#使用oledb讀取excel表格內(nèi)容到datatable的方法,涉及C#操作oledb及datatable的相關(guān)技巧,需要的朋友可以參考下2015-05-05