看了很多文章 目前很少有关于这部分的,主要是一搜索React Android 就是关于React Native的, 所以有必要记录一下, 也不知道用的是否是对的, 但是调通了
前端
React(16.8.6) + TypeScript(3.3.3) + JsBridge(1.0.4)
JsBridge
https://github.com/lzyzsd/JsBridge
index.html
把下面代码添加到入口文件index.html中,最后的window.bridge是把bridge添加到全局变量中:
<script type="text/javascript">
/*这段代码是固定的,必须要放到js中*/
function connectWebViewJavascriptBridge(callback) {
//Android使用
if (window.WebViewJavascriptBridge) {
callback(WebViewJavascriptBridge)
} else {
document.addEventListener(
'WebViewJavascriptBridgeReady'
, function () {
callback(WebViewJavascriptBridge)
},
false
);
}
//iOS使用
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 = 'wvjbscheme://__BRIDGE_LOADED__';
document.documentElement.appendChild(WVJBIframe);
setTimeout(function () { document.documentElement.removeChild(WVJBIframe) }, 0)
}
//在该function 中添加原生调起js方法
connectWebViewJavascriptBridge(function (bridge) {
bridge.init(function (message, responseCallback) {
console.log('JS got a message', message);
responseCallback(data);
});
window.bridge = bridge
}) </script>
Component中使用:
先声明一个全局变量:
declare global {
interface Window {
bridge:any
}
}
使用:
调用Native的方法"callNativeMethod"
window.bridge.callHandler('callNativeMethod','data',function(resp:any){
console.log('from native to js')
})
注册方法"getUserInfos" (由Native调用, 会回调到这里)
window.bridge.registerHandler("getUserInfos",function(data:any,responseCallback:any){
console.log('getUserInfos is called')
responseCallback('js callback to java');
});
Native实现
webview替换为BridgeWebView
注册handler
webView.registerHandler(
"callNativeMethod",
new BridgeHandler() {
@Override
public void handler(String data, CallBackFunction function) {
Log.d(TAG, "handler = addDrugReminder, data from web = " + data);
function.onCallBack("submitFromWeb exe, response data from Java");
}
});
Android调用JS
webView.callHandler(
"getUserInfos",
("userInfo"), new CallBackFunction() {
@Override
public void onCallBack(String data) {
Log.d(TAG, "onCallBack: "+data);
}
});
声明Client
class MyWebViewClient extends BridgeWebViewClient {
public MyWebViewClient(BridgeWebView webView) {
super(webView);
}
}
设置
webView.setWebViewClient(new MyWebViewClient(webView));
以上.
网友评论