https://github.com/lzyzsd/JsBridge
1.在使用WebViewJavascriptBridge 之前,先判断它是否存在,不存在,设置事件监听,监听WebViewJavascriptBridgeReady
if (window.WebViewJavascriptBridge) { //do your work here } else { document.addEventListener( 'WebViewJavascriptBridgeReady' , function() { //do your work here }, false ); }
2. js 调用 Java
1)在Java中注册监听
//submitFormWeb 是调用它的JS方法名
webView.registerHandler("submitFromWeb", new BridgeHandler() {
@Override
//data调用时传的参数,function Java方法执行后返回值 public void handler(String data, CallBackFunction function) { Log.i(TAG, "handler = submitFromWeb, data from web = " + data); function.onCallBack("submitFromWeb exe, response data from Java");//返回值 } });2)js 调用Java方法
WebViewJavascriptBridge.callHandler( 'submitFromWeb' , {'param': str1} , function(responseData) { document.getElementById("show").innerHTML = "send get responseData from java, data = " + responseData } );3)js调用默认的方法,不指定方法名
在Java代码中
webView.setDefaultHandler(new DefaultHandler());在JS中发送消息
window.WebViewJavascriptBridge.send( data , function(responseData) { document.getElementById("show").innerHTML = "repsonseData from java, data = " + responseData } );
2. Java 调用 js
1)js中注册方法等待调用
WebViewJavascriptBridge.registerHandler("functionInJs", function(data, responseCallback) { document.getElementById("show").innerHTML = ("data from Java: = " + data); var responseData = "Javascript Says Right back aka!"; responseCallback(responseData); });2)Java 中调用
webView.callHandler("functionInJs", new Gson().toJson(user), new CallBackFunction() { @Override public void onCallBack(String data) { } });3)或者是js 中使用默认方法init,Java中直接发消息
bridge.init(function(message, responseCallback) { console.log('JS got a message', message); var data = { 'Javascript Responds': 'Wee!' }; console.log('JS responding with', data); responseCallback(data); });webView.send("hello");