WebView中的JS交互是指在WebView(一个用于在应用程序中嵌入网页的视图)与原生应用代码之间进行JavaScript(JS)通信的过程。这种交互允许网页内容与原生应用的功能进行整合,从而提供更丰富、更动态的用户体验。
基础概念:
相关优势:
类型:
应用场景:
遇到的问题及解决方法:
示例代码(以Android为例):
WebView webView = findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(new WebAppInterface(this), "Android");
webView.loadUrl("file:///android_asset/index.html");
public class WebAppInterface {
Context mContext;
WebAppInterface(Context c) {
mContext = c;
}
@JavascriptInterface
public void showToast(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
}
<!DOCTYPE html>
<html>
<head>
<title>WebView JS交互示例</title>
<script type="text/javascript">
function showAndroidToast(toast) {
Android.showToast(toast);
}
</script>
</head>
<body>
<input type="button" value="点击显示Toast" onClick="showAndroidToast('Hello Android!')" />
</body>
</html>
领取专属 10元无门槛券
手把手带您无忧上云