美文网首页
WKWebView和JS交互使用

WKWebView和JS交互使用

作者: 我是三人禾 | 来源:发表于2017-02-24 13:20 被阅读63次

    越来越多的项目中使用Native和网页的混合开发,这使得纯客户端工作大大减轻。随着手机硬件的提升,软件卡顿问题也会越来越小。之前做web端交互的时候,用的WebViewJavascriptBridge的库,这个库十分强大,只是oc端和web端定好function的名称,就可以互通消息,但本篇只记录WKWebView原生代码交互,如果有错误,还请指教。

    • 加载本地html
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
        config.preferences.minimumFontSize = 18;
        self.wkWebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height/2) configuration:config];
        [self.view addSubview:self.wkWebView];
        NSString *filePath = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
        NSURL *baseURL = [[NSBundle mainBundle] bundleURL];
        [self.wkWebView loadHTMLString:[NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil] baseURL:baseURL];
    
    • OC端接收来着JS端发送的消息
      WKUserContentController,遵守@protocol WKScriptMessageHandler协议
        //  config.userContentController 点击去看到这属性是:  就是把前面这个和web视图联系起来
        WKUserContentController *userCC = config.userContentController;
        //JS调用OC 添加处理脚本
    /*! @abstract Adds a script message handler.
     @param scriptMessageHandler The message handler to add.
     @param name The name of the message handler.
     @discussion Adding a scriptMessageHandler adds a function
     window.webkit.messageHandlers.<name>.postMessage(<messageBody>) for all
     frames.
     */
        [userCC addScriptMessageHandler:self name:@"showMobile_qin"];
        [userCC addScriptMessageHandler:self name:@"showName"];
        [userCC addScriptMessageHandler:self name:@"showSendMsg"];
    
    #pragma mark - WKScriptMessageHandler
    
    - (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
        NSLog(@"userScripts:%@",userContentController.userScripts);
        NSLog(@"name:%@,,body:%@",message.name,message.body);
        if ([message.name isEqualToString:@"showSendMsg"]) {
            NSDictionary *dic = message.body;
            NSString *info = [NSString stringWithFormat:@"message是:%@",dic[@"message"]];
            NSLog(@"info:%@",info);
        }
    }
    
    • html端
    这是html互通消息端固定的格式写法
     window.webkit.messageHandlers.<name>.postMessage(<messageBody>) for all
    // JS代码  事件列表
            function btnClick() {
                var dic = {"message": "JS发消息给OC", "ls": "李四1" };
      window.webkit.messageHandlers.showSendMsg.postMessage(dic);
                }
    
    
    • 至此,js可以响应来自客服端的事件,而oc去响应的js端的事件更加简单。

    • OC代码

        [self.wkWebView evaluateJavaScript:@"alertSendMsg('OC端','呼唤')" completionHandler:^(id _Nullable other, NSError * _Nullable error) {
                    
                    NSLog(@"other:%@,error:%@",other,error);
                    
                }];
    
    • html代码
     <script>
        function alertSendMsg(num,msg) {
    document.getElementById('demo').innerHTML = '已接收' + num + ',' + msg + '!!'
                }
    </script>
    

    OK,大概就是这样,这个demo中,没有多么负责的功能,但是js 和oc 互通消息已经能做到了。

    demo地址

    相关文章

      网友评论

          本文标题:WKWebView和JS交互使用

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