.NET Core 3.1 WebBrowserControl read html after navigation

Viewed 4299

I Seem to be unable to read HTML after a WPF web browser control has finished navigating to a page.

The reason I have to use a WebBrowser instead of a HttpClient, is because the required web page requires logging into first.

XAML:

<WebBrowser x:Name="wbBrowse" Source="anywebpage" LoadCompleted="wbBrowse_LoadCompleted">
</WebBrowser>

Code:

  private void wbBrowse_LoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e)
  {
      var doc = wbBrowse.Document;
  }

I've tried casting Document to HtmlDocument but it crashes. It's a '{System.__ComObject}' object which means nothing to me.

Thanks

1 Answers

Add a reference to Microsoft HTML Object Library under Project->Add Reference->COM in Visual Studio and cast the value of Document to an MSHTML.IHTMLDocument2:

private void wbBrowse_LoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
    MSHTML.IHTMLDocument2 doc = wbBrowse.Document as MSHTML.IHTMLDocument2;
    ...
}

This does work in .NET Core 3.1.

Related