内容简介:注意: js调用android时的安全性(addJavascriptInterface):
- 1.通过WebView的loadUrl()
- 2.通过WebView的evaluateJavascript()
public static void runJsFunc(WebView webView,String funcName,@Nullable ValueCallback<String> 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<len; 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<String>() { @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); } } 复制代码
以上所述就是小编给大家介绍的《android webview总结》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Object-Oriented Design Heuristics
Arthur J. Riel / Addison-Wesley Professional / 1996-05-10 / USD 64.99
Product Description Here is the first object-oriented development book to provide specific experience-based guidelines to help developers make the right design decisions. This book offers the next ......一起来看看 《Object-Oriented Design Heuristics》 这本书的介绍吧!