WKWebView和H5的原生交互

核心代码

原生交互 WKWebView

1.原生调用H5方法
h5代码

methods: {
      setVersionCode(versionCode) {
        console.log('setVersionCode invoke versionCode -> ',versionCode)
        if (!Utils.isEmpty(versionCode)) {
          localStorage['versionCode'] = versionCode;
          console.log("setVersionCode - localStorage['versionCode'] -> ",localStorage['versionCode'])
        } else {
          console.e('客户端传递过来的versionCode 异常 -> ',versionCode)
        }
      },
      getVersionCode() {
        console.log('getVersionCode invoke')
        var u = navigator.userAgent;
        var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
        var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
        if (isAndroid) {
          window.android.invoke_native("getVersionCode", "", "jsGetUserInfoCallBack");
        } else if (isiOS) {
          // window.webkit.messageHandlers.getDevice.postMessage()
          window.location.href = 'cashloans://getVersionCode';
        }
      }
    },

ios端代码

在WKWebView中的执行回调代码方法中,拦截到h5中声明的方法getVersionCode,之后ios端调用h5声明的方法
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
   NSURL *URL = navigationAction.request.URL;
   NSString *urlString = [URL absoluteString];
  if([urlString rangeOfString:@"getVersionCode"].location !=NSNotFound){
   [self setVersionCode]; 
   decisionHandler(WKNavigationActionPolicyCancel);
    }
}
-(void)setVersionCode{
    
    NSString * versionCode =  [[[NSBundle mainBundle]infoDictionary] objectForKey:@"CFBundleShortVersionString"];
//原生声明的方法 setVersionCode
    NSString *jsMethod  = [NSString stringWithFormat:@"setVersionCode('%@')", versionCode];
    DLog(@"%@",jsMethod);
//WKUserScriptInjectionTimeAtDocumentStart : 注入时机为document的元素生成之后,其他内容load之前.
//WKUserScriptInjectionTimeAtDocumentEnd : 注入时机为document全部load完成,任意子资源load完成之前.
    WKUserScript *script =[[WKUserScript alloc] initWithSource:jsMethod injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:YES];
    [self.webView.configuration.userContentController addUserScript:script];
    
    [self.webView evaluateJavaScript:jsMethod completionHandler:^(id _Nullable response, NSError * _Nullable error) {
        DLog(@"%@",response);
        if (!error) { // 成功
            DLog(@"成功");
        } else { // 失败
            DLog(@"%@",error.localizedDescription);
        }
    }];

}


2.h5调用原生
ios端代码

  // 1. WKWebView注入ScriptMessageHandler
   [self.webView.configuration.userContentController addScriptMessageHandler:(id )self name:@"goSfz"];
// 从web界面中接收到一个脚本时调用
-(void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    DLog(@"%@",message.name);
    DLog(@"%@",message.body);
    if ([message.name isEqualToString:@"goSfz"]) { //实名认证
        
        NSDictionary *dict = [HttpTool dictionaryWithJsonString:message.body];
        self.cardType = [dict[@"cardType"] integerValue];
        
        [self startIDCardDetect];
        
        UserInfo *info = [[UserInfo alloc] init];
        info.userId = dict[@"userId"];
        info.token = dict[@"token"];
        [UserInfoManager updateAccount:info];
        
    }
}

h5端代码

var u = navigator.userAgent;
        var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
        var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
        let params = JSON.stringify({
          userId: JSON.parse(localStorage.userMes).userId,
          token: localStorage.token,
          cardType: type
        });
        if (isAndroid) {
          window.android.invoke_native("goSfz", params, "jsGetUserInfoCallBack");
        } else if (isiOS) {
//  window.webkit.messageHandlers.goSfz.postMessage(params) 固定格式 参数可以传递给客户端
          window.webkit.messageHandlers.goSfz.postMessage(params)
        }

你可能感兴趣的:(WKWebView和H5的原生交互)