Unable to access the DOM using WPF WebBrowser component

57 Views Asked by At

I am using the following code to get to the DOM of the web page. I am using the WPF WebBrowser component (not the WinForms one which works fine according to some posts). But with the WPF WebBrowser component, there is no way that I can figure it out. I am referencing mshtml assembly and according to some posts like this one I should have access to the DOM. But when I hover over the doc variable during debug, it displays a value of "System._ComObject" which is confusing. My goal is to highlight the search words in the DOM but cannot get access to it.

            IHTMLDocument2 doc = WebBrowserComponent.Document as IHTMLDocument2;
            if (doc != null)
            {
                StringBuilder html = new StringBuilder(doc.body.outerHTML);

                var words = SearchWords;
                foreach (String key in words)
                {
                    String substitution = "<span style='background-color: rgb(255, 255, 0);'>" + key + "</span>";
                    html.Replace(key, substitution);
                }
                doc.body.innerHTML = html.ToString();
            }
1

There are 1 best solutions below

0
DasiyTian_1203 On

I add a button to highlight the items refer to your code: Code for XAML:

 <StackPanel>
    <Button Content="HightLight" Click="Button_Click"> </Button>
    <WebBrowser x:Name="webBrowser" Source="https://www.bing.com/" Width="800" Height="380"/>
</StackPanel>

The cs code is:

  private void Button_Click(object sender, RoutedEventArgs e)
    {
        IHTMLDocument2 doc = webBrowser.Document as IHTMLDocument2;
        if (doc != null)
        {
            StringBuilder html = new StringBuilder(doc.body.outerHTML);
            dynamic document = webBrowser.Document;
            string str =  document.getElementById("sb_form_q").value;
            var words = new[] { str,"Bing" };
            foreach (String key in words)
            {
                String substitution = "<span style='background-color: rgb(255, 255, 0);'>" + key + "</span>";
                html.Replace(key, substitution);
            }
            doc.body.innerHTML = html.ToString();
            document.getElementById("sb_form_q").value = str;
        }
    }

And the result picture is below: enter image description here I can't reproduce the error, could you tell me which step that I missed?