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

坚强是说给别人听的谎言 提交于 2020-01-23 12:12:47

问题


I have created a Web Browser control in a TabControl.I want to set the Header of the TabItem to the Document's title of the Web Browser. I used the following code in the Navigated Event of the WebBrowser

dynamic doc = tabBrowser.Document; //tabBrowser is the name of WebBrowser Control
tab.Header = doc.Title;            //tab is the name of the Tab Item

But this piece of code doesn't work as it should.The header changes only for a few site. How can i set the Header of the tabItem to the Document's Title Value?

Here is the navigated function:

    public void tabBrowser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e) 
    { 
       urlTextBox.Text = tabBrowser.Source.ToString(); 
       myHistory.addToHistory(tabBrowser.Source.ToString());
       BookMarks.addBookmark(tabBrowser.Source.ToString()); 
       dynamic doc = tabBrowser.Document; 
       tab.Header = doc.Title; 
    }

回答1:


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



回答2:


This one will work

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



回答3:


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



来源:https://stackoverflow.com/questions/15819397/how-to-get-the-documents-title-from-a-web-browser-control-in-wpf

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