WKWebView与JS交互遇到的问题

错误信息

Error Domain=WKErrorDomain Code=4 "A JavaScript exception occurred" UserInfo={WKJavaScriptExceptionLineNumber=1, WKJavaScriptExceptionMessage=SyntaxError: Unexpected EOF, WKJavaScriptExceptionSourceURL=http://192.168.31.116:3000/getCustomPage?page=appweb, NSLocalizedDescription=A JavaScript exception occurred, WKJavaScriptExceptionColumnNumber=0

js调用OC方法时,我在执行这段代码后报上面的错误(method 是js代码)
[self.wkWebView evaluateJavaScript:method completionHandler:^(id _Nullable response, NSError * _Nullable error) {
            
            SLog(@"%@ %@",response,error);
        }];
造成这个错误的原因以及解决方案:
  • 1:你的js代码书写错误,我的js代码中含有空格和换行符导致这个错误的产生.
  • 2:当你执行- (void)evaluateJavaScript:(NSString *)javaScriptString completionHandler:(void (^ _Nullable)(_Nullable id, NSError * _Nullable error))completionHandler这个方法的时候一定要确认整个webView已经加载完成,所以这个方法应该写在webView的这个代理方法里面- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation;

最后附上示例代码

设置webView

  WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    config.preferences.minimumFontSize = 14;
    
    self.wkWebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, SScreenW, self.view.bounds.size.height) configuration:config];
    self.wkWebView.navigationDelegate = self;
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://192.168.31.116:3000/getCustomPage?page=appweb"]];
    [self.wkWebView loadRequest:request];
    [self.view addSubview:self.wkWebView];
    
    WKUserContentController *userCC = config.userContentController;
    //JS调用OC 添加处理脚本
    
    [userCC addScriptMessageHandler:self name:@"getUserInfo"];
#pragma mark - WKScriptMessageHandler

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    SLog(@"%@",NSStringFromSelector(_cmd));
    SLog(@"%@",message.body);
    SLog(@"%@",message.name);
   //message.body 为js传过来的参数数组
   //message.name 为js调用oc的方法名
   // getUserInfo 为js调用oc的方法名  [userCC addScriptMessageHandler:self name:@"getUserInfo"];
    if ([message.name isEqualToString:@"getUserInfo"]) {
        NSArray *array = message.body;
        NSString *methodStr = array.firstObject;
        _methodStr = methodStr;
    }
}
#pragma mark - WKNavigationDelegate
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    
    SUserModel *model = [[SUserInfoManager sharedManager] currentUserInfo];
    NSDictionary *dict = @{
                           @"Access_Token":model.Access_Token,
                           @"Avatar":model.Avatar,
                           @"UserName":model.UserName,
                           @"UserId":@(model.UserId),
                           //                               @"Remark":model.Remark,
                           };
// 将字典转化成JSON字符串
    NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
    NSString *paraStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    // 将JSON字符串转成无换行无空格字符串
    paraStr = [paraStr noWhiteSpaceString];
    NSString *method = [NSString stringWithFormat:@"%@('%@')",_methodStr,paraStr];
    SLog(@"%@",method);
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.15 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
// OC 调用JS方法 method 的js代码可往下看
        [self.wkWebView evaluateJavaScript:method completionHandler:^(id _Nullable response, NSError * _Nullable error) {
            
            SLog(@"%@ %@",response,error);
        }];
    });
    [SVProgressHUD dismiss];
}

noWhiteSpaceString

- (NSString *)noWhiteSpaceString {
    NSString *newString = self;
  //去除掉首尾的空白字符和换行字符
    newString = [newString stringByReplacingOccurrencesOfString:@"\r" withString:@""];
    newString = [newString stringByReplacingOccurrencesOfString:@"\n" withString:@""]; 
    newString = [newString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];  //去除掉首尾的空白字符和换行字符使用
    newString = [newString stringByReplacingOccurrencesOfString:@" " withString:@""];
//    可以去掉空格,注意此时生成的strUrl是autorelease属性的,所以不必对strUrl进行release操作!
    return newString;
}

method 的内容
getData('{"Access_Token":"zI1NiIsInR5cCI6IkCJ9.eyJzdWIiOiIzNjkxMDQxMTIiLCJqdGMzhmYmJjNC0xMTIwLTYwNy0yNjcxMzdiYzA4N2IiLCJpYXQiOjE0ODY1NDE5MzgsIk1lbWJlciI6Im5vcm1hbCIsIm5iZiI6MTQ4NjU0MTkzOCwiZXhwIjoxNDg3NzUxNTM4LCJpc3MiOiJhcHAuc2FtZWNpdHkucC5zYW1lY2l0eS5jb20uY24ifQ.ktcVYgZmkmnlxeTPT8r08H8hyrKdGy1vAfZxep6cA","UserId":304112,"Avatar":"http:\/\/ogo87xwp0.bkt.clouddn.com\/member\/avatar\/imgs\/girl.jpg","UserName":"用户7871383550"}')

你可能感兴趣的:(WKWebView与JS交互遇到的问题)