How to get the Document's Title from a Web Browser control in wpf

a 夏天 提交于 2019-12-06 08:38:20

In my code I used LoadCompleted event of WebBrowser. Probably in your Navigated Event document still not ready and document title not right or empty.

private void MyWebBrowser_LoadCompleted_1(object sender, NavigationEventArgs e)
{
    try
    {
        MyTextBox.Text = MyWebBrowser.Source.ToString();
        Title_doc.Content = ((dynamic)MyWebBrowser.Document).Title;
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

This one will work

var docTitle = document.getElementsByTagName("title")
    .Cast<IHTMLElement>()
    .FirstOrDefault().innerText; 

The (dynamic)Document cast fails atleast when the Document changes during the operation (Operation can't complete, NotSupportedException, reason 8070000c), which happens if user clicks links too fast.

Found another plausible solution based on the Wpf webbrowser disable external links question UPDATE 2 link https://social.technet.microsoft.com/wiki/contents/articles/22943.preventing-external-links-from-opening-in-new-window-in-wpf-web-browser.aspx

The DWebBrowserEvents has TitleChanged event which seems to work reliably, so adapt the code from there, and add handler to this event.

wbEvents.TitleChange += new SHDocVw.DWebBrowserEvents_TitleChangeEventHandler(OnWebBrowserTitleChanged);

The handler has just one argument, new title as string.

void OnWebBrowserTitleChanged(string title)
{
     // Set title where you want
}

A bit heavy, but i needed both of these to work...

That linked code has other issues, like adding the event handlers again on every LoadCompleted event of WebBrowser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!