加载URL
_hbqWebView = [[UIWebView alloc] initWithFrame:self.view.bounds];
_hbqWebView.delegate = self;
[_hbqWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.jianshu.com/"]]];
[self.view addSubview:_hbqWebView];
不加载特定的URL
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
if ([request.URL isEqual:[NSURL URLWithString:@"http://www.jianshu.com/"]]) {
NSLog(@"no");
return NO;
}
NSLog(@"yes");
return YES;
}
UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;
- (void)webViewDidStartLoad:(UIWebView *)webView;
- (void)webViewDidFinishLoad:(UIWebView *)webView;
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
OC调用JavaScript
- stringByEvaluatingJavaScriptFromString:
- (void)webViewDidFinishLoad:(UIWebView *)webView {
NSLog(@"finish");
self.navigationItem.title = [_hbqWebView stringByEvaluatingJavaScriptFromString:@"document.title"];
}
- JavaScriptCore(iOS 7.0 +)
- (void)webViewDidFinishLoad:(UIWebView *)webView {
//获取该UIWebView的javascript上下文
JSContext *jsContext = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
//在调用前,设置异常回调
[jsContext setExceptionHandler:^(JSContext *context, JSValue *exception){
NSLog(@"HBQ____%@", exception);
}];
//这也是一种获取标题的方法。
JSValue *value = [jsContext evaluateScript:@"document.titlexxxx"];
//更新标题
self.navigationItem.title = value.toString;
}
JavaScript调用OC
- Custom URL Scheme(拦截URL)
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
//标准的URL包含scheme、host、port、path、query、fragment等
NSURL *URL = request.URL;
if ([URL.scheme isEqualToString:@"darkangel"]) {
if ([URL.host isEqualToString:@"smsLogin"]) {
NSLog(@"短信验证码登录,参数为 %@", URL.query);
return NO;
}
}
return YES;
}
·············