本文共 1685 字,大约阅读时间需要 5 分钟。
1.通过WebView的loadUrl()
2.通过WebView的evaluateJavascript()
public static void runJsFunc(WebView webView,String funcName,@Nullable ValueCallback callback, Object... params){
if(TextUtils.isEmpty(funcName)){
return;
}
if(webView == null){
return;
}
StringBuilder builder = new StringBuilder(funcName);
builder.append("(");
if(params != null && params.length >0){
int len = params.length;
for (int i = 0; i
Object param = params[i];
String str = "";
if(param != null){
if(param instanceof String){
str = "\""+param.toString()+"\"";
}else {
str = param.toString();
}
}
builder.append(str);
if(i != len-1){
builder.append(",");
}
}
}
builder.append(")");
String jsFunc = builder.toString();
XLogUtil.d("jsFunc:"+jsFunc);
webView.post(() -> {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
//4.4版本以上,调用带返回值js方法
webView.evaluateJavascript(jsFunc, new ValueCallback() {
@Override
public void onReceiveValue(String value) {
XLogUtil.d("jsFunc :"+jsFunc +",onReceiveValue:"+value);
if(callback != null){
callback.onReceiveValue(value);
}
}
});
}else {
webView.loadUrl("javascript:" + jsFunc);
}
});
}
复制代码
JS调用 Android 代码的方法有3种:一般用第一种
1.通过WebView的addJavascriptInterface()进行对象映射
2.通过 WebViewClient 的shouldOverrideUrlLoading ()方法回调拦截 url
3.通过 WebChromeClient 的onJsAlert()、onJsConfirm()、onJsPrompt()方法回调拦截JS对话框alert()、confirm()、prompt() 消息
注意: js调用android时的安全性(addJavascriptInterface):
public static void keepsafe(WebView webView,boolean debugable){
if (Build.VERSION.SDK_INT > 10 &&Build.VERSION.SDK_INT < 17) {
webView.removeJavascriptInterface("searchBoxJavaBridge_");
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
WebView.setWebContentsDebuggingEnabled(debugable);
}
}
复制代码
转载地址:http://ddcpo.baihongyu.com/