本文实例总结了C#的WEBBROWSER与JS交互的方法。分享给大家供大家参考。具体实现方法如下:
[b]一、实现WebBrowser内部跳转,阻止默认打开IE[/b]
[b]1、引用封装好的WebBrowserLinkSelf.dll实现
[/b]
[url=#]
}
}
}
//4、删除节点
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>");
[b]2、数据交互
[/b]
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#程序设计有所帮助。