JsBridge实现JS交互(JSBridge)

一、安装JsBridge

第三方库下载地址:JsBridge

maven安装:

repositories {
    // ...
    maven { url "https://jitpack.io" }
}

dependencies {
    compile 'com.github.lzyzsd:jsbridge:1.0.4'
}

二、初始化代码

// 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();
      });
  }
// Android初始化代码
mWeb.registerHandler("getOS", new BridgeHandler() {
    @Override
    public void handler(String data, CallBackFunction function) {
        HashMap response = new HashMap(){{
            put("error", 0);
            put("message", "");
            put("data", new HashMap(){{
                put("os", "android");
            }});
        }};
        function.onCallBack(response.toString());
    }
});
mWeb.registerHandler("login", new BridgeHandler() {
    @Override
    public void handler(String data, CallBackFunction function) {
        Gson gson = new Gson();
        final User user = gson.fromJson(data, User.class);
        HashMap response = new HashMap(){{
            put("error", 0);
            put("message", "");
            put("data", String.format("执行登录操作,账号为:%s、密码为:%s", user.getAccount(), user.getPassword()));
        }};
        function.onCallBack(response.toString());
    }
});

三、原生调用JS

// 使用callHandler的方式调用JS中已经注册过的方法
mWeb.callHandler("jsbridge_getJsMessage", message, new CallBackFunction() {
    @Override
    public void onCallBack(String data) {
        showNativeMessage(String.format("原生调用JsBridge方法后,Js方法的返回值为:【%s】", data));
    }
});

四、JS调用原生

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

发表评论