要在Android WebViewClient中处理JavaScript的Alerts和Prompt,您可以按照以下步骤进行操作:
public class MyWebViewClient extends WebViewClient {
@Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
// 处理JavaScript的Alert
AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
builder.setMessage(message)
.setPositiveButton(android.R.string.ok, null)
.setCancelable(false)
.show();
result.confirm(); // 确认弹窗已被处理
return true;
}
@Override
public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
// 处理JavaScript的Prompt
AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
builder.setMessage(message);
final EditText input = new EditText(view.getContext());
input.setText(defaultValue);
builder.setView(input);
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
result.confirm(input.getText().toString()); // 获取用户输入的值并返回给JavaScript
}
});
builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
result.cancel(); // 用户取消输入,返回null给JavaScript
}
});
builder.setCancelable(false);
builder.show();
return true;
}
}
WebView webView = (WebView) findViewById(R.id.webView);
webView.setWebViewClient(new MyWebViewClient());
这样,当网页中有JavaScript的Alert或Prompt弹窗时,Android WebViewClient会拦截并处理它们,并显示相应的对话框供用户交互。
上一篇:Android WebViewClient / WebViewAssetLoader实现错误
下一篇:Android WebViewClient中的onReceivedClientCertRequest方法只被调用一次。