美文网首页
Objective-C与JS交互 —— WKWebView拦截U

Objective-C与JS交互 —— WKWebView拦截U

作者: MaxWellPro | 来源:发表于2017-07-20 17:38 被阅读119次

    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);
        }];
    }
    

    相关文章

      网友评论

          本文标题:Objective-C与JS交互 —— WKWebView拦截U

          本文链接:https://www.haomeiwen.com/subject/rodjkxtx.html