WebViewJavascriptBridge实现与JS交互(JsBridge)

一、安装WebViewJavascriptBridge

第三方库下载地址:WebViewJavascriptBridge

pod安装:

pod 'WebViewJavascriptBridge', '~> 6.0'

二、初始化代码

// JS初始化代码
/**
 * 初始化jsbridge
 * @param readyCallback 初始化完成后的回调
 */ function initJsBridge(readyCallback) {
     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终端
     // 注册jsbridge
     function connectWebViewJavascriptBridge(callback) {
         if (isAndroid) {
             if (window.WebViewJavascriptBridge) {
                 callback(WebViewJavascriptBridge)
             } else {
                 document.addEventListener(
                     'WebViewJavascriptBridgeReady'
                     , function () {
                         callback(WebViewJavascriptBridge)
                     },
                     false
                 );
             }
             return;
         }
         if (isiOS) {
             if (window.WebViewJavascriptBridge) {
                 return callback(WebViewJavascriptBridge);
             }
             if (window.WVJBCallbacks) {
                 return window.WVJBCallbacks.push(callback);
             }
             window.WVJBCallbacks = [callback];
             var WVJBIframe = document.createElement('iframe');
             WVJBIframe.style.display = 'none';
             WVJBIframe.src = 'https://__bridge_loaded__';
             document.documentElement.appendChild(WVJBIframe);
             setTimeout(function () {
                 document.documentElement.removeChild(WVJBIframe)
             }, 0)
         }
     }
     // 调用注册方法
     connectWebViewJavascriptBridge(function (bridge) {
         if (isAndroid) {
             bridge.init(function (message, responseCallback) {
                 console.log('JS got a message', message);
                 responseCallback(data);
             });
         }
          
         // 只有在这里注册过的方法,在原声代码里才能用callHandler的方式调用
         bridge.registerHandler('jsbridge_showMessage', function (data, responseCallback) {
             showResponse(data);
         });
         bridge.registerHandler('jsbridge_getJsMessage', function (data, responseCallback) {
              showResponse(data);
              responseCallback('native 传过来的是:' + data);
          });

          readyCallback();
      });
  }
// iOS初始化代码
 - (void)setupJsBridge {
  if (self.bridge) return;
  // self.webview既可以是UIWebView,又可以是WKWebView
  self.bridge = [WebViewJavascriptBridge bridgeForWebView:self.webView];
  
  [self.bridge registerHandler:@"getOS" handler:^(id data, WVJBResponseCallback responseCallback) {
      // 这里Response的回调可以传id类型数据,但是为了保持Android、iOS的统一,全部使用json字符串作为返回数据
      NSDictionary *response = @{@"error": @(0), @"message": @"", @"data": @{@"os": @"ios"}};
      responseCallback([response jsonString]);
  }];
  
  [self.bridge registerHandler:@"login" handler:^(id data, WVJBResponseCallback responseCallback) {
      if (data == nil || ![data isKindOfClass:[NSDictionary class]]) {
          NSDictionary *response = @{@"error": @(-1), @"message": @"调用参数有误"};
          responseCallback([response jsonString]);
          return;
      }
      
      NSString *account = data[@"account"];
      NSString *passwd = data[@"password"];
      NSDictionary *response = @{@"error": @(0), @"message": @"登录成功", @"data" : [NSString stringWithFormat:@"执行登录操作,账号为:%@、密码为:@%@", account, passwd]};
      responseCallback([response jsonString]);
  }];
}

三、原生调用JS

[self.bridge callHandler:@"jsbridge_getJsMessage" data:@"点击了原生的按钮22" responseCallback:^(id responseData) {
  UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"显示jsbridge返回值" message:responseData delegate:nil cancelButtonTitle:@"好" otherButtonTitles:nil, nil];
   [alert show];
}];

四、JS调用原生

// 首先调用JSBridge初始化代码,完成后再设置其他
initJsBridge(function () {
  $("#getOS").click(function () {
        // 通过JsBridge调用原生方法,写法固定,第一个参数时方法名,第二个参数时传入参数,第三个参数时响应回调
        window.WebViewJavascriptBridge.callHandler('getOS', null, function (response) {
        showResponse(response);
      });
  });
 });

发表评论