How to get the Document's Title from a Web Bro

2019-05-23 06:13发布

问题:

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;