在Android开发中,回调JavaScript通常涉及到WebView与JavaScript之间的交互。WebView是Android提供的一个组件,用于在应用程序中显示网页内容,而JavaScript则是一种运行在浏览器中的脚本语言,用于增强网页的交互性。
基础概念:
优势:
类型:
loadUrl("javascript:...")
方法执行JavaScript代码。addJavascriptInterface()
方法将Java对象注入到WebView中,JavaScript可以通过特定的接口调用Java方法。应用场景:
问题及解决方法:
问题:在Android 4.2以下版本中,使用addJavascriptInterface()
存在安全风险,因为JavaScript可以调用任何公共方法,可能导致安全漏洞。
解决方法:
@JavascriptInterface
注解来标记允许JavaScript调用的方法,这样只有标记了该注解的方法才会被暴露给JavaScript。示例代码:
// Android端代码
public class WebAppInterface {
Context mContext;
/** Instantiate the interface and set the context */
WebAppInterface(Context c) {
mContext = c;
}
/** Show a toast from the web page */
@JavascriptInterface
public void showToast(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
}
WebView webView = (WebView) findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(new WebAppInterface(this), "Android");
webView.loadUrl("file:///android_asset/index.html");
// HTML/JavaScript端代码
<!DOCTYPE html>
<html>
<head>
<title>Test Page</title>
<script type="text/javascript">
function showAndroidToast(toast) {
Android.showToast(toast);
}
</script>
</head>
<body>
<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" />
</body>
</html>
在这个例子中,当用户点击HTML页面上的按钮时,会调用JavaScript函数showAndroidToast()
,该函数又会调用Android端的showToast()
方法,从而在Android应用中显示一个Toast消息。
注意事项:
addJavascriptInterface()
。@JavascriptInterface
的方法才会被JavaScript访问。领取专属 10元无门槛券
手把手带您无忧上云