• 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 = "<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='#' title='替换标签' >替换</a>";
                        }
                    }
                }
    
                //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>");
    

      2、数据交互

    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);
            }
        }

       源码:https://files.cnblogs.com/NotAnEmpty/wpf_WebBorwser.rar

  • 相关阅读:
    POJ 1149 PIGS(Dinic最大流)
    HDU 4514 湫湫系列故事——设计风景线(并查集+树形DP)
    [kuangbin带你飞]专题十一 网络流个人题解(L题留坑)
    BZOJ 3931 网络吞吐量(最短路+拆点最大流)
    学习RMQ-ST表
    `这个符号在mysql中的作用
    用一条mysql语句插入多条数据
    Leetcode 257 Binary Tree Paths 二叉树 DFS
    Leetcode 203 Remove Linked List Elements 链表
    Leetcode 38 Count and Say 传说中的递推
  • 原文地址:https://www.cnblogs.com/NotAnEmpty/p/4103649.html
Copyright © 2020-2023  润新知