WKWebView 与 UIWebView 拦截URL 的处理方式基本一样。除了代理方法和WKWebView的使用不太一样。
WKWebView拦截URL
- 1.设置WebView的navigationDelegate
self.webView.navigationDelegate = self;
- 2.通过scheme识别WebView的URL
#pragma mark - WKNavigationDelegate
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
NSURL *URL = navigationAction.request.URL;
NSString *scheme = [URL scheme];
if ([scheme isEqualToString:@"JSAction://"]) {
[self handleCustomAction:URL];
decisionHandler(WKNavigationActionPolicyCancel);
return;
}
decisionHandler(WKNavigationActionPolicyAllow);
}
- 3.JS调用OC
function locationClick() {
loadURL("JSAction://getLocation");
}
- 4.OC处理URL
#pragma mark - private method
- (void)handleCustomAction:(NSURL *)URL
{
NSString *host = [URL host];
if ([host isEqualToString:@"getLocation"]) {
[self getLocation];
}
}
- 5.OC将结果返回给JS
- (void)getLocation {
// 获取位置信息
···
// 将结果返回给js
NSString *loactionStr = [NSString stringWithFormat:@"setLocation('%@')",@"广东省深圳市南山区高新南一道TCL大厦"];
[self.webView evaluateJavaScript:loactionStr completionHandler:^(id _Nullable result, NSError * _Nullable error) {
NSLog(@"%@----%@",result, error);
}];
}