目录
1 网页的3种弹窗
1.1 Alert警示弹窗
1.2 Confirm确认弹窗
1.3 Prompt输入弹窗
2 WebView支持弹窗
2.1 onJsAlert
2.2 onJsConfirm
2.3 onJsPrompt
AndroidApp内嵌一个WebView用于承载网页,WebView会监听拦截网页的3种弹窗(Alert,Confirm,Prompt),如果不做任何处理,表现出来的形式就好像是不支持网页弹窗,其实是支持的!
1 网页的3种弹窗
所有的弹窗都由3部分组成:Title(标题),Message(内容),Button(按钮)
1.1 Alert警示弹窗
只有一个"确定"按钮,点击关闭弹窗
alert('卢本伟NB!');
1.2 Confirm确认弹窗
有2个按钮,点击"确定"返回true,点击"取消"返回false
let flag = confirm('卢本伟NB吗?');
1.3 Prompt输入弹窗
有2个按钮,1个输入框,点击"确定"返回输入框内容(无内容返回空字符串),点击"取消"返回null
let context = prompt('卢本伟斗地主什么水平?');
2 WebView支持弹窗
支持3种弹窗,需要对WebView对象设置webView.setWebChromeClient(重写的WebChromeClient对象)
2.1 onJsAlert
mainWebView.setWebChromeClient(new WebChromeClient() {@Overridepublic boolean onJsAlert(WebView view, String url, String message, JsResult result) {AlertDialog.Builder builder = new AlertDialog.Builder(WebViewActivity.this);// 将message设置在Tittle位置,更显眼builder.setTitle(message);// builder.setMessage(message);builder.setPositiveButton("知道了", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {// 返回确认result.confirm();}});// 点击对话框外面和点击返回键,不能取消弹窗builder.setCancelable(false);builder.show();return true;}
}
2.2 onJsConfirm
mainWebView.setWebChromeClient(new WebChromeClient() {@Overridepublic boolean onJsConfirm(WebView view, String url, String message, JsResult result) {AlertDialog.Builder builder = new AlertDialog.Builder(WebViewActivity.this);// 将message设置在Tittle位置,更显眼builder.setTitle(message);// builder.setMessage(message);// 设置肯定按钮builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {// 返回确认result.confirm();// 解除对话框dialog.dismiss();}});// 设置否定按钮'builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {// 返回取消result.cancel();// 解除对话框dialog.dismiss();}});// 点击对话框外面和点击返回键,不能取消弹窗builder.setCancelable(false);builder.show();return true;}
}
2.3 onJsPrompt
mainWebView.setWebChromeClient(new WebChromeClient() {@Overridepublic boolean onJsPrompt(WebView view, String url, String message, String defaultValue, final JsPromptResult result) {AlertDialog.Builder builder = new AlertDialog.Builder(WebViewActivity.this);// 将message设置在Tittle位置,更显眼builder.setTitle(message);// builder.setMessage(message);final EditText editText = new EditText(WebViewActivity.this);editText.setText("");//设置默认数据builder.setView(editText); //为弹出窗口设置输入框// 设置肯定按钮builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {result.confirm(editText.getText().toString());//向Javascript传递输入值}});// 设置否定按钮builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {result.cancel();}});// 点击对话框外面和点击返回键,不能取消弹窗builder.setCancelable(false);builder.show();return true;}
}