Getting the title of a Web View in Cocoa Touch

In an application I’m working on, I display a UIWebView with a navigation bar. I wanted to display the title of the web page in the navigation bar when I load a page, but there doesn’t appear to be any obvious way to do it.

There’s actually a very easy way to get the title (or any other property) of a page in a web view: stringByEvaluatingJavaScriptFromString:.

In this case, I use the delegate method webViewDidFinishLoad to obtain the page title and set the title of the navigation bar,

- (void)webViewDidFinishLoad:(UIWebView *)webView
    NSString* title = [webView stringByEvaluatingJavaScriptFromString: @"document.title"];
    navbar.title = title;

The result looks like this:

iPhone Simulator
Uploaded with plasq‘s Skitch!

Leave a Reply