JavaScript 调用 Android 浏览器通常涉及到在网页中使用 JavaScript 与 Android 设备的原生功能进行交互。这种交互可以通过多种方式实现,以下是一些基础概念和相关信息:
@JavascriptInterface
注解标记方法,以便 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();
}
}
// 在 Activity 中设置 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>
Android 端代码:
// 在 Activity 中处理自定义 URL scheme
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = getIntent();
if (Intent.ACTION_VIEW.equals(intent.getAction())) {
Uri uri = intent.getData();
if (uri != null && uri.toString().startsWith("myapp://")) {
// 处理自定义 URL scheme
}
}
}
HTML 和 JavaScript 端代码:
<!DOCTYPE html>
<html>
<head>
<title>Test Page</title>
<script type="text/javascript">
function openApp() {
window.location.href = "myapp://open";
}
</script>
</head>
<body>
<input type="button" value="Open App" onClick="openApp()" />
</body>
</html>
问题: 安全性问题,如 XSS 攻击。
解决方法:
@JavascriptInterface
注解时,确保方法不会执行危险操作。问题: 性能问题,WebView 加载缓慢。
解决方法:
通过以上方法和注意事项,可以有效地实现 JavaScript 调用 Android 浏览器的功能,并确保应用的安全性和性能。
领取专属 10元无门槛券
手把手带您无忧上云