下面演示如何在 iOS 中獲取當前網頁的 URL、title 和 HTML 內容。
[objc]
@property (strong, nonatomic) UIWebView *webView;
@property (strong, nonatomic) NSString *currentURL;
@property (strong, nonatomic) NSString *currentTitle;
@property (strong, nonatomic) NSString *currentHTML;
[objc]
-(void) webViewDidFinishLoad:(UIWebView *)webView {
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
self.title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];//獲取當前頁面的 title
self.currentURL = webView.request.URL.absoluteString;
NSLog(@"title-%@--url-%@--", self.title, self.currentURL);
NSString *lJs = @"document.documentElement.innerHTML";//獲取當前網頁的 html
self.currentHTML = [webView stringByEvaluatingJavaScriptFromString:lJs];
}
透過 webViewDidFinishLoad: 回調,利用 stringByEvaluatingJavaScriptFromString: 執行 JavaScript 取得頁面標題與 HTML,並從 webView.request.URL 讀取當前網址。