目标
实现Native与JS页面的相互调用
- JS从Native调取Token
- JS调取Native跳转
- Native调取当前JS里的消息信息、用户信息等
- JS掉起Native支付页面,Native支付完成(失败)后回调给JS
实现框架 (Android 、iOS、JS)
android参考:https://github.com/lzyzsd/JsBridge、https://github.com/hjhrq1991/JsBridge
iOS参考:https://github.com/LOVEGLXR/WebNewsJSBridgeOC
JS接入方法:参考android或iOS的任何一个即可
示例代码<支付>
H5
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="initial-scale=1, user-scalable=0, minimal-ui">
<title></title>
</head>
<script type="text/javascript" src="/res/common/js/jquery.js"></script>
<p>
<input type="button" id="enter" value="调起支付" onclick="click1();"
/>
</p>
<br/>
<script>
// 声明初始化JSBridge失败数据
var default_data = {
error: "1"
};
//声明 connect_JSBridge
var connectMerchantJSBridge = function (callback) {
try {
if (window.WebViewJavascriptBridge) {
callback(WebViewJavascriptBridge);
} else {
document.addEventListener("TestJavascriptBridgeReady", function () {
callback(WebViewJavascriptBridge);
}, false);
}
} catch (ex) { }
};
//声明 cmb_JSBridge
var cmbMerchantBridge = {
initSignNet: function (payData,name) {
if (!payData) {
payData = default_data;
}
connectMerchantJSBridge(function (bridge) {
if (typeof bridge === "undefined") {
return;
}
bridge.callHandler(name, JSON.stringify(payData));
});
},
};
//注册调用本页面方法
connectMerchantJSBridge(function(bridge) {
bridge.init(function(message, responseCallback) {
});
//支付成功回调
bridge.registerHandler("onPaySuccess", function(data, responseCallback) {
console.log(data)
});
//支付失败回调
bridge.registerHandler("onPayFail", function(data, responseCallback) {
console.log(data)
});
})
//注册调起支付
window.cmbMerchantBridge = cmbMerchantBridge;
function click1()
{
try {
cmbMerchantBridge.initSignNet("ercode", "requestPay");
} catch (ex) { }
}
</script>
</body>
</html>
Android
1.根据 桥名称 TJJavascriptBridge 注册 JsBridge
webView.setDefaultHandler(new DefaultHandler());
webView.setCustom("TJJavascriptBridge");
2.注册JS调用Native的方法:requestPay
webView.registerHandler("requestPay", (data, function) -> {
//跳转到支付页面
});
3.支付完成(或失败)后回调JS
//微信支付成功通过EventBus回调
@Subscribe(threadMode = ThreadMode.MAIN)
public void onPayEvent(PayEvent event) {
if (event.isSuccess) {
webView.callHandler("onPaySuccess", "", data -> {
});
} else {
webView.callHandler("onPayFail", event.failurReason, data -> {
});
}
}
iOS
1.引入 WebViewJavascriptBridge 并注册到 UIWebview
@property WebViewJavascriptBridge* bridge;
[WebViewJavascriptBridge enableLogging];
_bridge = [WebViewJavascriptBridge bridgeForWebView:_mWebView webViewDelegate:self handler:nil];
2.注册JS调用Native的方法:requestPay
[_bridge registerHandler:@"requestPay" handler:^(id data, WVJBResponseCallback responseCallback) {
//跳转到支付页面
}];
3.支付完成(或失败)后回调JS
- (void) onPaySuccess{
[_bridge callHandler:@"onPaySuccess"];
}
- (void) onPayFail{
[_bridge callHandler:@"onPayFail" data:@"失败原因:***"];
}
网友评论