1.导入
项目地址 https://github.com/lzyzsd/JsBridge
虽然4,5年没有维护了,但是老牌的,就是好用,8.6k的赞,值得信赖
repositories {
// ...
maven { url "https://jitpack.io" }
}
dependencies {
compile 'com.github.lzyzsd:jsbridge:1.0.4'
}
2.H5页面代码
<!DOCTYPE html>
<html lang="en">
<head>
<title>JSBridge</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
</head>
<body>
<button onclick="myClick(1)">获取内容</button>
<button onclick="myClick(2)">返回首页</button>
<a href="tel:12345">打电话</a>
</body>
<script>
function myClick(actionType) {
window.WebViewJavascriptBridge.callHandler(
'jsCallNative', {
'actionType': actionType
}, function(responseData) {
alert(responseData);
}
);
}
//JS注册事件监听
function connectWebViewJavascriptBridge(callback) {
var u = navigator.userAgent;
var isApp = u.indexOf('myApp') > -1; // app打开
var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; // android终端
var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); // ios终端
if (isApp && isAndroid) {
if (window.WebViewJavascriptBridge) {
callback(WebViewJavascriptBridge)
} else {
document.addEventListener(
'WebViewJavascriptBridgeReady', function() {
callback(WebViewJavascriptBridge)
},
false
);
}
}
if (isApp && 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) {
bridge.init(function(message, responseCallback) {});
})
</script>
</html>
3.Android页面代码
3.1 布局页面
使用BridgeWebView,(BridgeWebView extends WebView)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.github.lzyzsd.jsbridge.BridgeWebView
android:id="@+id/wv"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
3.2Activity代码
wv.registerHandler("jsCallNative", (data, function) -> {
try {
JSONObject dataJsonObject = JSON.parseObject(data);
if (dataJsonObject != null) {
String key = dataJsonObject.getString("actionType");
if ("1".equals(key)) { // 获取
JSONObject jsonObject = new JSONObject();
jsonObject.put("content", "hello js");
function.onCallBack(jsonObject.toJSONString());
} else if ("2".equals(key)) { // 返回
finish();
}
}
} catch (Exception e) {
e.printStackTrace();
}
});
// 配置 WebView
WebSettings webSettings = wv.getSettings();
webSettings.setDomStorageEnabled(true);
webSettings.setLoadWithOverviewMode(true);
webSettings.setUseWideViewPort(true);
webSettings.setBlockNetworkImage(false);
webSettings.setJavaScriptEnabled(true);
webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
webSettings.setUserAgentString(webSettings.getUserAgentString() + " myApp" + " version" + BuildConfig.VERSION_NAME);
BridgeWebViewClient bridgeWebViewClient = new BridgeWebViewClient(wv) {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.contains("tel:")) {
// 拨打电话
return true;
}
return super.shouldOverrideUrlLoading(view, url);
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
String title = view.getTitle();
if (!TextUtils.isEmpty(title)) {
tvTitle.setText(title);
}
}
};
wv.setWebViewClient(bridgeWebViewClient);
wv.loadUrl("http://www.aaaaa.com/b.html");
4.注意点
1.因为H5的按钮,本来就有自己的逻辑,建议修改UserAgent来实现判断
我这里是在UserAgent后面拼接一个特定的字符串,让H5用来区分。
webSettings.setUserAgentString(webSettings.getUserAgentString() + " myApp" + " version" + BuildConfig.VERSION_NAME);
2.WebViewClient要用BridgeWebViewClient
BridgeWebViewClient bridgeWebViewClient = new BridgeWebViewClient(wv){
......
};
wv.setWebViewClient(bridgeWebViewClient);
3.传递数据问题
一般我们交互数据的时候,都是传一个Json。
但是App给H5返回内容是function.onCallBack(String data)只有传字符串的方法,但是iOS是可以传对象的,所以需要让iOS将对象转成字符串传过去。然后让H5用Json解析。
网友评论