How can I get the page title in WebBrowser control?
How can I get the page title in a WebBrowser control when I navigate to different websites?
xmlns
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
Properties starting with D
DataContext
DesiredSize
Dispatcher
DoubleTap
xaml tag
<phone:WebBrowser Name="browser" Height="760" VerticalAlignment="Top"></开发者_如何学Cphone:WebBrowser>
I had the same problem. @Akash Kava's answer is almost correct but this is the correct javascript to read the html title:
String title = (string)browser.InvokeScript("eval", "document.title.toString()");
For me the following code works. The answers from @Akash and @Mikko set me on the right path, but I still had some problems with a few websites. The problem as I understand it is that the Navigated event is raised when the WebBrowser
component starts getting data from the remote server. As such the DOM object is not yet complete, so calling the document.title
throws an error. So I just retry after a few milliseconds till I get the title. This "loop" has never iterated more than 3 times on any website I tested and flawlessly brought me the title every time.
private void webBrowser1_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
ThreadPool.QueueUserWorkItem(UpdateText);
}
private void UpdateText(object o)
{
Thread.Sleep(100);
Dispatcher.BeginInvoke(() =>
{
try
{
textBlock1.Text = webBrowser1.InvokeScript("eval", "document.title").ToString();
}
catch (SystemException)
{
ThreadPool.QueueUserWorkItem(UpdateText);
}
});
}
I'm pretty sure that
String title = browser.Document.Title;
should do the trick.
See here.
All answers are not 100% correct:
You must call the following:
String title = (string)browser.InvokeScript("eval", "document.title.toString()");
in the LoadCompleted event of the browser, and not in the navigated event.
You can use InvokeScript to get title as,
String title = browser.InvokeScript("document.title");
I don't know it's correct or not but you can try window.title too.
The code below works for me, note the navigated event, if you use loaded it will trigger just before the page is loaded, you want that to trigger sometime "after" the page is Fully Loaded, navigated acts as that event.
private void web1_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
//Added thread using "using System.Thread", to act as a buffer for any page delay.
Thread.Sleep(2000);
String title = (string)web1.InvokeScript("eval", "document.title");
PageTitle.Text = title;
}
精彩评论