How to Get the Title of a HTML Page Displayed in UIWebView?
I need to extract the contents of the title tag from an HTML page displayed in a UIWebView. What is the most robust means of doing so?
I know I can do:
- (void)webViewDidFinishLoad:(UIWebView *)webView{
NSString *theTitle=[webView stringByEvaluatingJavaScriptFromString:@"document.title"];
}
However, that only works if javascript is enabled.
Alternatively, I could just scan the text of the HTML code for the title but that feels a bit cumbersome and might prove fragile if the page's authors got freaky with their code. If it comes to that, what's the best method to use for processing the html text within the iPhone API?
I feel that I've forgotten something obvious. Is there a better method than these two choices?
Update:
Following from the answer to this question: UIWebView: Can You Disable Javascript? there appears to be no way to turn off Javascript in UIWebView. Therefore the Javascript method above will always work.
For those who just scroll down to find the answer:
- (void)webViewDidFinishLoad:(UIWebView *)webView{
NSString *theTitle=[webView stringByEvaluatingJavaScriptFromString:@"document.title"];
}
This will always work as there is no way to turn off Javascript in UIWebView.
If Javascript Enabled Use this :-
NSString *theTitle=[webViewstringByEvaluatingJavaScriptFromString:@"document.title"];
If Javascript Disabled Use this :-
NSString * htmlCode = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.appcoda.com"] encoding:NSASCIIStringEncoding error:nil];
NSString * start = @"<title>";
NSRange range1 = [htmlCode rangeOfString:start];
NSString * end = @"</title>";
NSRange range2 = [htmlCode rangeOfString:end];
NSString * subString = [htmlCode substringWithRange:NSMakeRange(range1.location + 7, range2.location - range1.location - 7)];
NSLog(@"substring is %@",subString);
I Used +7 and -7 in NSMakeRange to eliminate the length of <title>
ie 7
WKWebView
has 'title' property, just do it like this,
func webView(_ wv: WKWebView, didFinish navigation: WKNavigation!) {
title = wv.title
}
I don't think UIWebView
is suitable right now.