美文网首页
ios WKWebView和js交互

ios WKWebView和js交互

作者: coder小鹏 | 来源:发表于2022-01-06 19:02 被阅读0次

    WKWebViewConfiguration注入WKScriptMessageHandler,由前端下发数据,客户端根据相关的数据作出相应的操作,OC代码如下:

    • wkWebView懒加载
    - (WKWebView *)wkWebView {
        if (!_wkWebView) {
            // 进行配置控制器
            WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
            // 实例化对象
            configuration.userContentController = [WKUserContentController new];
            // 调用JS方法
            [configuration.userContentController addScriptMessageHandler:self name:@"NativeModel"];
            
            // 进行偏好设置
            WKPreferences *preferences = [WKPreferences new];
            preferences.javaScriptCanOpenWindowsAutomatically = YES;
    //        preferences.minimumFontSize = 20.0;
            configuration.preferences = preferences;
            
            // 初始化WKWebView
            _wkWebView = [[WKWebView alloc]initWithFrame:CGRectMake(0, kNavigationBarHeight, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height) configuration:configuration];
            
            _wkWebView.UIDelegate = self;
            
            _wkWebView.navigationDelegate =self;
            
        }
        return _wkWebView;
    }
    
    • 添加到当前视图上,并加载相应的链接
    [self.view addSubview:self.wkWebView];
    [self.wkWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@""]]];
    
    • 遵守相应的协议
    @interface ViewController ()<WKScriptMessageHandler,WKNavigationDelegate,WKUIDelegate>
    
    //webView
    @property (nonatomic, strong) WKWebView *wkWebView;
    
    @end
    
    
    • 实现WKScriptMessageHandler代理方法,并在该代理方法中根据相应的注入js的名称,实现对应的逻辑
    - (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
        if ([message.name isEqualToString:@"NativeModel"]) {
            NSDictionary *jsData = message.body;
            NSLog(@"%@", message.name);
            //读取js function的字符串
    //        NSString *jsFunctionString = jsData[@"result"];
    //        //拼接调用该方法的js字符串(convertDictionaryToJson:方法将NSDictionary转成JSON格式的字符串)
    //        NSString *jsonString = [NSDictionary convertDictionaryToJson:@{@"test":@"123", @"data":@"666"}];
    //        NSString *jsCallBack = [NSString stringWithFormat:@"(%@)(%@);", jsFunctionString, jsonString];
    //        //执行回调
    //        [self.weWebView evaluateJavaScript:jsCallBack completionHandler:^(id _Nullable result, NSError * _Nullable error) {
    //            if (error) {
    //                NSLog(@"err is %@", error.domain);
    //            }
    //        }];
        }
    }
    

    前端代码如下

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>html5page-oc</title>
    
        <script>
            function btn1Click() {
                window.webkit.messageHandlers.NativeModel.postMessage({name: 'zhangyutang', age: 12});
                alert("after call");
            }
        </script>
    
    </head>
    <body>
    
    <input type="button" value="button c" onclick="btn1Click()">
    
    </body>
    </html>
    

    使用WKWebViewjs传值

    OC代码如下

    • wkWebView懒加载
    - (WKWebView *)wkWebView {
        if (!_wkWebView) {
            // 进行配置控制器
            WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
            // 实例化对象
            configuration.userContentController = [WKUserContentController new];
            // 调用JS方法
            [configuration.userContentController addScriptMessageHandler:self name:@"NativeModel"];
            
            // 进行偏好设置
            WKPreferences *preferences = [WKPreferences new];
            preferences.javaScriptCanOpenWindowsAutomatically = YES;
    //        preferences.minimumFontSize = 20.0;
            configuration.preferences = preferences;
            
            // 初始化WKWebView
            _wkWebView = [[WKWebView alloc]initWithFrame:CGRectMake(0, kNavigationBarHeight, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height) configuration:configuration];
            
            _wkWebView.UIDelegate = self;
            
            _wkWebView.navigationDelegate =self;
            
        }
        return _wkWebView;
    }
    
    • 添加到当前视图上,并加载相应的链接
    [self.view addSubview:self.wkWebView];
    [self.wkWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@""]]];
    
    • 遵守相应的协议
    @interface ViewController ()<WKScriptMessageHandler,WKNavigationDelegate,WKUIDelegate>
    
    //webView
    @property (nonatomic, strong) WKWebView *wkWebView;
    
    @end
    
    
    • 实现代理方法,在协议加载完WebView后,注入相应的js,将需要上传的参数上传给前端
    - (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
    {
        NSMutableDictionary *dic = [NSMutableDictionary new];
        dic[@"username"] = @"里斯";
        dic[@"token"] = @"1198203";
        dic[@"avatar"] = @"";
        
        NSString *jsonStr = [self convertToJsonData:dic];
        
        NSString * jsStr = [NSString stringWithFormat:@"sendKey('%@')",jsonStr];
        
        [self.wkWebView evaluateJavaScript:jsStr completionHandler:^(id _Nullable result, NSError * _Nullable error) {
            
            //此处可以打印error.
            
            
        }];
    }
    
    -(NSString *)convertToJsonData:(NSDictionary *)dict
    
    {
        
        NSError *error;
        
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
        
        NSString *jsonString;
        
        if (!jsonData) {
            
            NSLog(@"%@",error);
            
        }else{
            
            jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
            
        }
        
        NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
        
        NSRange range = {0,jsonString.length};
        
        //去掉字符串中的空格
        
        [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
        
        NSRange range2 = {0,mutStr.length};
        
        //去掉字符串中的换行符
        
        [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
        
        return mutStr;
        
    }
    

    前端代码如下

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
    </head>
    
    <body>
        <div onclick="newway()">新方法</div>
        <input type="text" id = "show1">
        <input type="text" id = "show2">
        <input type="text" id = "show3">
    </body>
    <script src="js/jquery-2.1.4.js"></script>
    <script>
      function newway(){
        alert("newway")
        // var val = '{"token":"1198203","username":"张三","avatar":""}'
        // sendKey(val)
      }
    
      function sendKey(val){
        alert("sendKey")
        let iOSInfo = JSON.parse(val);
    
        $("#show1").val(iOSInfo.username)
        $("#show2").val(iOSInfo.token)
        $("#show3").val(iOSInfo.avatar)
    
      }
     
    </script>
    </html>
    
    

    遇到的问题

    • 上传参数到前端,注入js时出现Error Domain=WKErrorDomain Code=4 "A JavaScript exception occurred" UserInfo={NSLocalizedDescription=A JavaScript exception occurred错误,检查上传的JSON是否正确,保证上传的JSON是一个正确的JSON即可

    相关文章

      网友评论

          本文标题:ios WKWebView和js交互

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