采用WebView实现安卓手机OA时,OA系统中有js的alert、confirm、window.open()不起作用。要点:重载WebChromeClient类;实现alert对应的onJsAlert,confirm对应的onJsConfirm,window.open对应的onCreateWindow;setSupportMultipleWindows支持弹出窗口;setWebViewClient支持在webview上打开连接。
使用webView. setWebChromeClient(new WebChromeClient())
当webView. setWebChromeClient(new WebChromeClient())后,默认已实现alert和confirm方法。但是提示窗口标题有带url,而且window.open没有反应。要自定义alert和confirm窗口和实现window.open需要重载WebChromeClient。
新建类MyWebChromeClient,继承WebChromeClient
(一)重载onJsAlert方法实现js的alert
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
final AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
builder.setTitle("OA提示信息")
.setMessage(message)
.setPositiveButton("确定", null)
.setCancelable(false)
.create()
.show();
result.confirm();
return true;
}
当用WebView访问一个网页,带有javascript的alert提示时,出现的效果
(二) 重载onJsConfirm方法实现js的confirm
public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
final AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
builder.setTitle("OA确认信息")
.setMessage(message)
.setPositiveButton("确定", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
result.confirm();
}
}).setNeutralButton("取消", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
result.cancel();
}
})
.create()
.show();
return true;
}
(三) 重载onCreateWindow方法实现js的window.open
public WebView newWebView = null;
@Override
public boolean onCreateWindow(WebView view, boolean dialog, boolean userGesture, Message resultMsg) {
newWebView = new WebView(view.getContext());
view.addView(newWebView);
WebSettings settings = newWebView.getSettings();
settings.setJavaScriptEnabled(true);
//这个setWebViewClient要加上,否则window.open弹出浏览器打开。
newWebView.setWebViewClient(new WebViewClient());
newWebView.setWebChromeClient(this);
WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
transport.setWebView(newWebView);
resultMsg.sendToTarget();
return true;
}
(三) 重载onCloseWindow方法实现js的window.close
public void onCloseWindow(WebView view) {
if (newWebView != null) {
newWebView.setVisibility(View.GONE);
view.removeView(newWebView);
}
}
(四)修改MainActivity的onCreateView
WebSettings setting = webView1.getSettings();
setting.setJavaScriptEnabled(true);
//没有setSupportMultipleWindows的话window.open不会增加新窗口
setting.setSupportMultipleWindows(true);
//没有setWebViewClient的话点连接会采用浏览器打开
webView1.setWebViewClient(new WebViewClient());
webView1.setWebChromeClient(new MyWebChromeClient());
webView1.loadUrl(sUrl);