C#的WEBBROWSER与JS交互小结

C#的WEBBROWSER与JS交互小结
时间: 2014-12-31 08:10 / 围观: 30 / 评论数:条 / 分类:脚本编程
本文实例总结了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
代码如下:
    {
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);
}
}
 
二、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 = “”;
//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 = “替换”;
}
}
}
//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 = “”;
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(“write new html”);
2、数据交互
代码如下:
public MainWindow()
{
InitializeComponent();
this.webBrowser.ObjectForScripting = new ScriptEvent();
this.webBrowser.NavigateToString(@””);
}
[System.Runtime.InteropServices.ComVisible(true)]
public class ScriptEvent
{
//供JS调用
public void ShowMessage(string message)
{
MessageBox.Show(message);
}
}
希望本文所述对大家的C#程序设计有所帮助。
 
标签:des   class   style   com   代码   使用   http   si   java   
原地址:http://www.jb51.net/article/57574.htm
本文实例总结了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
复制代码代码如下:
    {
        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);
        }
    }
 
 
二、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 = "";
 //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 = "替换";
         }
     }
 }
 
 //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 = "";
 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("write new html");
 
2、数据交互
复制代码代码如下:
public MainWindow()
    {
        InitializeComponent();
        this.webBrowser.ObjectForScripting = new ScriptEvent();
        this.webBrowser.NavigateToString(@"");
    }
 
[System.Runtime.InteropServices.ComVisible(true)]
public class ScriptEvent
{
    //供JS调用
    public void ShowMessage(string message)
    {
        MessageBox.Show(message);
    }
}
 
posted @ 2022-07-27 10:36  devgis  阅读(59)  评论(0编辑  收藏  举报