WebView与JavaScript交互分为两种
一.Android客户端去调用JS代码
1.1WebView通过loadUrl()
1.2.通过WebView的evaluateJavascript()
1.1/1.2WebView通过loadUrl(),evaluateJavascript()实例:
imageimage
新建HTML方法:
java —>new Folder—>Assets Folder
assets —>file—>evaluate.html
test.html:
<html>
<head>
<title>WebView</title>
<script type="text/javascript">
function callJS(){
<!-- getElementById() 方法可返回对拥有指定 ID 的第一个对象的引用。 innerHTML 设置或者返回元素的内容-->
document.getElementById("test").innerHTML="点击alert返回元素";
alert("Android调用了JS的callJS方法实现'webview.setWebChromeClient'才响应");
}
</script>
</head>
<body>
<div id="test">Android通过WebView调用JS代码</div>
</body>
</html>
MainActivity.java:
WebView webView;
Button buttonLeft;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main4);
webView=findViewById(R.id.webview);
buttonLeft = findViewById(R.id.btnLeft);
WebSettings webSettings=webView.getSettings();
webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);//缓存
webSettings.setJavaScriptEnabled(true);
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);//允许弹窗
webView.getSettings().setDomStorageEnabled(true);
webView.loadUrl("file:///android_asset/evaluate.html");
buttonLeft.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
webView.post(new Runnable() {
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
public void run() {
// webView.evaluateJavascript("javascript:callJS()", new ValueCallback<String>() {
// @Override
// public void onReceiveValue(String s) {
// buttonLeft.setText(s);
// }
// });
webView.loadUrl("javascript:callJS()");
}
});
}
});
//比较完善的webView控件
webView.setWebChromeClient(new WebChromeClient(){
@Override
public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
AlertDialog.Builder builder=new AlertDialog.Builder(Main4Activity.this);
builder.setTitle("alert1");
builder.setMessage(message);
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
result.confirm();
}
});
builder.setCancelable(false);
builder.create().show();
return true;
}
});
}
布局文件:
<WebView
android:id="@+id/webview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"></WebView>
<Button
android:id="@+id/btnLeft"
android:text="点我"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:ignore="MissingConstraints" />
03dff0d62c06c0de43e2930c4c5d331.jpg
0b95744fc7b4d106baaf0988b6f1ea9.jpg
4cf5b6ccb0cce0cc4b8ac7b9f584366.jpg
网友评论