美文网首页
WKWebView与js交互

WKWebView与js交互

作者: 呆呆羞 | 来源:发表于2017-09-20 11:25 被阅读0次

    WKWebView与js交互

    //  ViewController.m
    #import "ViewController.h"
    #import <WebKit/WebKit.h>
    
    @interface ViewController () <WKScriptMessageHandler,WKNavigationDelegate>
    
    @property (nonatomic, strong) WKWebView *wkWebView;
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        //创建一个webiview的配置项
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    
        // 通过js与webview内容交互配置
        config.userContentController = [[WKUserContentController alloc] init];
        //在状态栏显示或隐藏,活动指示器,默认为NO
        [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
        // 默认是不能通过JS自动打开窗口的,必须通过用户交互才能打开
        config.preferences.javaScriptCanOpenWindowsAutomatically = YES;
        
        self.wkWebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height/2) configuration:config];
        
        self.wkWebView.navigationDelegate=self;
        
        
        
        NSString *filePath = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
        NSURL *baseURL = [[NSBundle mainBundle] bundleURL];
    //加载本地的html
        [self.wkWebView loadHTMLString:[NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil] baseURL:baseURL];
     
        [self.view addSubview:self.wkWebView];
    
        //
        WKUserContentController *userCC = config.userContentController;
        //OC注册供JS调用的方法
        /*
         window.webkit.messageHandlers.showMobile.postMessage
         [userCC addScriptMessageHandler:self name:@"showMobile"];
         这两行代码是对应的。
         
         */
        [userCC addScriptMessageHandler:self name:@"HtmlActivationAPPforNull"];
        [userCC addScriptMessageHandler:self name:@"HtmlActivationAPPforBookName"];
        [userCC addScriptMessageHandler:self name:@"HtmlActivationAPPforData"];
        
    }
    - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
        NSLog(@"铺抓加载前的URL的来源=%@",webView.URL);
        NSLog(@"铺抓加载前的URL=%@",navigationAction.request.URL);
        return decisionHandler(WKNavigationActionPolicyAllow);
    }
    - (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        NSLog(@"完成加载啦");
    }
    
    
    /**
     //网页加载完成之后调用JS代码才会执行,因为这个时候html页面已经注入到webView中并且可以响应到对应方法
    
     @param sender 用Storyboard建的三个button
     */
    - (IBAction)btnClick:(UIButton *)sender {
        
        if (!self.wkWebView.loading) {
            if (sender.tag == 123) {
                 NSLog(@"按钮123《APP触发HTML界面》被点击");
                [self.wkWebView evaluateJavaScript:@"APPActivationHtml()" completionHandler:^(id _Nullable response, NSError * _Nullable error) {
                    //TODO
                    NSLog(@"response=%@ 。error=%@",response,error);
                }];
            }
            
            if (sender.tag == 234) {
                 NSLog(@"按钮234《APP触发并给HTML传参数》被点击");
                [self.wkWebView evaluateJavaScript:@"alertName('除了问号这一段文字都是APP传给html的')" completionHandler:nil];
            }
            
            if (sender.tag == 345) {
                 NSLog(@"按钮345《APP触发并给HTML传多个参数》被点击");
                [self.wkWebView evaluateJavaScript:@"alertSendMsg('18870707070','周末OC')" completionHandler:nil];
                [self showMsg:@"懂了吗"];
    
            }
    
        } else {
            NSLog(@"the view is currently loading content");
        }
    }
    
    #pragma mark - WKScriptMessageHandler
    
    - (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
        
        NSLog(@"%@",NSStringFromSelector(_cmd));
        NSLog(@"message.name=%@",message.name);
        NSLog(@"message.body=%@",message.body);
    
        if ([message.name isEqualToString:@"HtmlActivationAPPforNull"]) {
            [self showMsg:@"我是HTML触发,APP的原生提示框"];
        }
        if ([message.name isEqualToString:@"HtmlActivationAPPforBookName"]) {
            NSString *info = [NSString stringWithFormat:@"书名号中的文字《%@》, 是HTML传给APP",message.body];
            [self showMsg:info];
        }
        
        if ([message.name isEqualToString:@"HtmlActivationAPPforData"]) {
            NSArray *array = message.body;
            NSString *info = [NSString stringWithFormat:@"书名号中文字都是Html传给app的《%@》,《 %@》",array.firstObject,array.lastObject];
            
          [self.wkWebView evaluateJavaScript:@"alertNam('OCOC')" completionHandler:nil];
    
            [self showMsg:info];
        }
    }
    
    - (void)showMsg:(NSString *)msg {
        
        [[[UIAlertView alloc] initWithTitle:nil message:msg delegate:nil cancelButtonTitle:nil otherButtonTitles:@"点击OK", nil] show];
        _wkWebView.backgroundColor =[UIColor blueColor];
        
    }
    - (IBAction)clear:(id)sender {
        NSLog(@"清除被点击");
        [self.wkWebView evaluateJavaScript:@"clear('清除你')" completionHandler:nil];
    }
    
    
    @end
    
    Snip20170920_3.png

    本地的html代码:

    <html>
        <!--描述网页信息-->
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
            <title>我的HTML</title>
            <style>
                *{
                    font-size: 50px;
                }
            
                .btn{height:80px; width:80%; padding: 0px 30px; background-color: #0071E7; border: solid 1px #0071E7; border-radius:5px; font-size: 1em; color: white}
            </style>
            
            <script>
                function clear() {
                    document.getElementById('mobile').innerHTML = ''
                    document.getElementById('name').innerHTML = ''
                    document.getElementById('msg').innerHTML = ''
                }
            
                //OC调用JS的方法列表
                function APPActivationHtml() {
                    //alert('我是上面的小黄 手机号是:')
                    document.getElementById('mobile').innerHTML = '这段话是HTML上的'
                }
    
                function alertName(msg) {
                    //alert('你好 ' + msg + ', 我也很高兴见到你')
                    document.getElementById('name').innerHTML = '????' + msg + ''
                }
    
                function alertSendMsg(num,msg) {
                    
                    document.getElementById('msg').innerHTML = 'APP同时传两个参数给html页面,参数一:' + num + ',参数二:' + msg + '!!'
                }
            
                //JS响应方法列表
                function btnClick1() {
                    window.webkit.messageHandlers.HtmlActivationAPPforNull.postMessage(null)
                }
    
                function btnClick2() {
                    window.webkit.messageHandlers.HtmlActivationAPPforBookName.postMessage('追风筝的人')
                }
    
                function btnClick3() {
                    
                    window.webkit.messageHandlers.HtmlActivationAPPforData.postMessage
                    (['HTML页面的文字'])
                    
                }
    
            </script>
            
        </head>
    
        <!--网页具体内容-->
        <body>
            <br/>
    
            <div>
                <label>白色为HTML页面</label>
            </div>
            <br/>
    
            <div id="mobile"></div>
            <div>
                <button class="btn" type="button" onclick="btnClick1()">HTML页面触发原声APP</button>
            </div>
            <br/>
            
            <div id="name"></div>
            <div>
                <button class="btn" type="button" onclick="btnClick2()">HTML页面传给APP</button>
            </div>
            <br/>
            
            <div id="msg"></div>
            <div>
                <button class="btn" type="button" onclick="btnClick3()">HTML页面的按钮C</button>
            </div>
    
    
        </body>
    </html>
    
    如果文章帮到您,喜欢点个赞,谢谢您。
    文章内容出错,记得留言,感激不尽。

    相关文章

      网友评论

          本文标题:WKWebView与js交互

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