Summary of WEBBROWSER and JS interaction of C

  • 2020-12-09 00:58:39
  • OfStack

This article summarizes the WEBBROWSER and JS interaction methods of C#. Share to everybody for everybody reference. Specific implementation methods are as follows:

1. Realize WebBrowser internal jump to prevent IE from opening by default

1. Reference the encapsulated WebBrowserLinkSelf. dll implementation

public partial class MainWindow : Window
{
       private WebBrowser webBrowser = new WebBrowser();
 
       public MainWindow()
       {
           InitializeComponent();
 
            this.webBrowser.LoadCompleted += new LoadCompletedEventHandler(webBrowser_LoadCompleted);
 
           // make webbrowser Is hosted by Label On the implementation webborwser Internal jump, no IE Open the
           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, reference com: Microsoft Internet Controls implementation (reference 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>

2. Interaction between WebBrowser and JS

1. Interaction with page labels

// reference Microsoft.mshtml
 
 //1 , add 1 a html Tag to id for lg the div In the
 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 , set id for su The label of the value Values and style
 //2.1 use setAttribute
 HTMLDocument doc = (HTMLDocument)this.webBrowser.Document;
 IHTMLElement search = doc.getElementById("su");
 IHTMLDOMAttribute att = search.getAttribute("value") as IHTMLDOMAttribute;
 search.setAttribute("value", " baidu 1 Under the ");
 //search.click();
 search.style.display = "none";
 //2.2 use outerHtml
 search.outerHTML = "<input id=\"su\" value=\" baidu 1 Under the \" class=\"bg s_btn\" type=\"submit\" onclick=\"alert(' baidu 1 Under the ');\" />";
 //2.3 use IHTMLDOMAttribute
 IHTMLAttributeCollection attributes = (search as IHTMLDOMNode).attributes as IHTMLAttributeCollection;
 foreach (IHTMLDOMAttribute attr in attributes)
 {
     if (attr.nodeName == "value")
     {
         attr.nodeValue = " baidu 1 Under the ";
     }
 }
 
//3 Class styles were applied mnav the a The label
 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=' Replace the label ' > replace </a>";
         }
     }
 }
 
 //4 , delete node
 HTMLDocument doc = (HTMLDocument)this.webBrowser.Document;
 IHTMLElement search = doc.getElementById("su");
 IHTMLDOMNode node = search as IHTMLDOMNode;
 node.parentNode.removeChild(node);
 
 //5 , JS The event
 //5.1 add JS
 HTMLDocument doc = (HTMLDocument)this.webBrowser.Document;
 IHTMLElement search = doc.getElementById("su");
 search.outerHTML = "<input id=\"su\" value=\" baidu 1 Under the \" class=\"bg s_btn\" type=\"submit\" onclick=\"onClick();\" />";
 IHTMLScriptElement scriptErrorSuppressed = (IHTMLScriptElement)doc.createElement("script");
 scriptErrorSuppressed.type = "text/javascript";
 scriptErrorSuppressed.text = "function onClick(){ alert(' add js'); }";
 IHTMLElementCollection nodes = doc.getElementsByTagName("head");
 foreach (IHTMLElement elem in nodes)
 {
     var head = (HTMLHeadElement)elem;
     head.appendChild((IHTMLDOMNode)scriptErrorSuppressed);
 }
 //5.2 delete JS
 IHTMLElementCollection scripts = (IHTMLElementCollection)doc.getElementsByName("script");
 foreach (IHTMLElement node in scripts)
 {
     if (!(node is IHTMLUnknownElement))
     {
         IHTMLScriptElement script = node as IHTMLScriptElement;
         // Delete all js File reference
         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. Data interaction

public MainWindow()
    {
        InitializeComponent();
        this.webBrowser.ObjectForScripting = new ScriptEvent();
        this.webBrowser.NavigateToString(@"<html><head><title>Test</title></head><body><input type=""button"" value="" Click on the "" onclick=""window.external.ShowMessage(' baidu 1 Under the ');"" /></body></html>");
    }
 
[System.Runtime.InteropServices.ComVisible(true)]
public class ScriptEvent
{
    // for JS call
    public void ShowMessage(string message)
    {
        MessageBox.Show(message);
    }
}

I hope this article has been helpful for your C# programming.


Related articles: