美文网首页
OC与JS的交互(WKWebview-MessageHandle

OC与JS的交互(WKWebview-MessageHandle

作者: 温水煮青蛙a | 来源:发表于2018-01-11 16:17 被阅读0次

    GitHub:https://github.com/1205665266/WKWebView

    HTML代码
    <!DOCTYPE html>
    <html>
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=utf8">
                <script language="javascript">
    
                //JS执行window.webkit.messageHandlers.Share.postMessage(<messageBody>)
                function shareClick() {
                    window.webkit.messageHandlers.Share.postMessage({title:'测试分享的标题',content:'测试分享的内容',url:'https://github.com/maying1992'});
                }
                
                //分享回调结果显示
                function shareResult(channel_id,share_channel,share_url) {
                    var content = channel_id+","+share_channel+","+share_url;
                    alert(content);
                    document.getElementById("returnValue").value = content;
                }
                
                //JS执行window.webkit.messageHandlers.Camera.postMessage(<messageBody>)
                function cameraClick() {
                    window.webkit.messageHandlers.Camera.postMessage(null);
                }
                
                //调用相册回调结果显示
                function cameraResult(result) {
                    alert(result);
                    document.getElementById("returnValue").value = result;
                }
                
            
                    </script>
                </head>
        
        <body>
            <h1>这是按钮调用</h1>
            <input type="button" value="分享" onclick="shareClick()" />
            <input type="button" value="相机" onclick="cameraClick()" />
    
            <h1>回调展示区</h1>
            <textarea id ="returnValue" type="value" rows="5" cols="40">
                
            </textarea>
        </body>
    </html>
    
    创建WKWebView代码
    //
    //  BaseWebViewController.m
    //  Capp
    //
    //  Created by apple on 2017/10/18.
    //  Copyright © 2017年 apple. All rights reserved.
    //
    
    #import "BaseWebViewController.h"
    #import <WebKit/WebKit.h>
    
    @interface BaseWebViewController ()<WKNavigationDelegate,WKUIDelegate,WKScriptMessageHandler>
    
    @end
    
    @implementation BaseWebViewController
    {
        WKWebView *_webView;
    }
    
    - (void)dealloc {
        
        NSLog(@"web 走了 dealloc");
        //这里remove掉 添加的js标识
        [[_webView configuration].userContentController removeScriptMessageHandlerForName:@"Camera"];
    }
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        //技术文档    
        self.view.backgroundColor = [UIColor whiteColor];
        self.navigationItem.title = self.titleStr;
        [self setupUI];
    
    }
    
    //导航左返回
    -(void)leftBarButtonAction
    {
        if (_webView.canGoBack) {
            [_webView goBack];
        }else{
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
    
    - (void)setupUI {
        
        WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
        WKUserContentController *userContentController = [[WKUserContentController alloc] init];
        //这里add 添加的js标识  用于处理接受的js通知做判断
        [userContentController addScriptMessageHandler:self name:@"Camera"];
        
        configuration.userContentController = userContentController;
        
        _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, kWIDTH, kHEIGHT-64) configuration:configuration];
        
        //    _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, kWIDTH, kHEIGHT-64)];
        _webView.navigationDelegate = self;
        _webView.UIDelegate = self;
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.urlStr]];
        [_webView loadRequest:request];
        _webView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:_webView];
        [_webView setOpaque:NO];
    }
    
    #pragma mark - UIWebViewDelegate   uiwebview代理方法
    - (void)webViewDidStartLoad:(UIWebView *)webView {
        [_progressLayer startLoad];
    }
    
    - (void)webViewDidFinishLoad:(UIWebView *)webView {
        [_progressLayer finishedLoad];
        //自动获取  webView的title
    //    self.navigationItem.title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    }
    
    - (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
        [_progressLayer finishedLoad];
    }
    
    -(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
    {
        //    NSLog(@"request.URL---%@",request.URL);
        //    NSLog(@"request.description(str)---%@",request.description);
        //点击
        if (navigationType == UIWebViewNavigationTypeLinkClicked) {
            
        }
        return YES;
    }
    
    #pragma mark <WKNavigationDelegate>   WKWebView代理方法
    // 页面开始加载时调用
    - (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation
    {
       
    }
    
    // 页面加载完成之后调用
    - (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
    {
        //自动获取  webView的title
    //    self.navigationItem.title = webView.title;
    }
    
    //页面加载失败时 调用
    - (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error
    {
       
    }
    
    // 接收到服务器跳转请求之后调用
    - (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation
    {
        NSLog(@"=======接收到服务器跳转请求之后调用======");
    }
    
    /**
     *  在发送请求之前,决定是否跳转
     *
     *  @param webView          实现该代理的webview
     *  @param navigationAction 当前navigation
     *  @param decisionHandler  是否调转block
     */
    - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
    {
        NSLog(@"````````````在发送请求之前,决定是否跳转```````````");
        NSLog(@"IP地址=======%@", navigationAction.request.URL.host.lowercaseString);
        NSLog(@"======request.URL.absoluteString---%@",navigationAction.request.URL.absoluteString);
        NSLog(@"======request.description(str)---%@",navigationAction.request.description);
        if ([navigationAction.request.URL.absoluteString containsString:@"collectionStore"]) {//
            
            //在这里做特定的操作
            decisionHandler(WKNavigationActionPolicyCancel);
        }else{
            decisionHandler(WKNavigationActionPolicyAllow);
        }
    }
    
    /**
     *  在收到响应后,决定是否跳转
     *
     *  @param webView            实现该代理的webview
     *  @param navigationResponse 当前navigation
     *  @param decisionHandler    是否跳转block
     */
    - (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler
    {
        NSLog(@"============在收到响应后,决定是否跳转========");
        NSLog(@"IP地址=======%@", navigationResponse.response.URL.host.lowercaseString);
        NSLog(@"request.URL.absoluteString---%@",navigationResponse.response.URL.absoluteString);
        NSLog(@"request.description(str)---%@",navigationResponse.response.description);
        decisionHandler(WKNavigationResponsePolicyAllow);
    }
    
    #pragma mark - WKUIDelegate
    - (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler
    {
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提醒" message:message preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            completionHandler();
        }]];
        
        [self presentViewController:alert animated:YES completion:nil];
    }
    
    #pragma mark - WKScriptMessageHandler
    - (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
    {
        NSLog(@"message.name:%@", message.name);
        NSLog(@"message.body:%@", message.body);
        
        //根据添加的js标识   做特定的操作
        if ([message.name isEqualToString:@"Camera"]) {
            
        }
        if ([message.name isEqualToString:@"ShowMessageFromWKWebView"]) {
            //        [self showMessageWithParams:message.body];
        }
    }
    
    #pragma mark - OC传数据给JS
    - (void)showMessageWithParams:(NSDictionary *)dict {
        
        if (![dict isKindOfClass:[NSDictionary class]]) {
            return;
        }
        
        // 将结果返回给js  oc调用js   
        //注:showMessageResult('%@')", @"message传到OC成功,oc传数据给js"
        //showMessageResult是js的方法名
        // ('%@') 是 传给js的参数
        NSString *returnJSStr = [NSString stringWithFormat:@"showMessageResult('%@')", @"message传到OC成功,oc传数据给js"];
        [_webView evaluateJavaScript:returnJSStr completionHandler:^(id _Nullable result, NSError * _Nullable error) {
            
            NSLog(@"oc调用js回调,,result==%@,error==%@", result, error);
        }];
    }
    
    @end
    
    

    相关文章

      网友评论

          本文标题:OC与JS的交互(WKWebview-MessageHandle

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