WebView 有两个非常重要的辅助类,WebViewClient和WebViewChromeCient,先介绍这两个类的用区别
WebViewClient主要帮助WebView处理各种通知、请求事件的.
onLoadResource
onPageStart
onPageFinish
onReceiveError
onReceivedHttpAuthRequest
WebChromeClient主要辅助WebView处理Javascript的对话框、网站图标、网站title、加载进度.
onCloseWindow
关闭WebViewonCreateWindow()
onJsAlert
WebView上alert无效,需要定制WebChromeClient处理弹出onJsPrompt
onJsConfirm
onProgressChanged
onReceivedIcon
onReceivedTitle
代码:
public class MainActivity extends AppCompatActivity {
private WebView mWvContent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWvContent = (WebView) findViewById(R.id.id_wv_content);
mWvContent.loadUrl("http://sina.com.cn"); // 访问网页
// 获取设置
WebSettings settings = mWvContent.getSettings();
// 设置支持JavaScript脚本
settings.setJavaScriptEnabled(true);
// 支持文件访问
settings.setAllowFileAccess(true);
// 支持缩放
settings.setBuiltInZoomControls(true);
settings.setSupportZoom(true);
// 帮助WebView处理各种通知和请求事件
mWvContent.setWebViewClient(new WebViewClient() {
// 是在浏览器中跳转还是在此WebView中跳转
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
// 加载页面资源时调用
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
Toast.makeText(MainActivity.this, "onPageStarted: " + url, Toast.LENGTH_SHORT).show();
}
});
// 辅助WebView处理JS事件
mWvContent.setWebChromeClient(new WebChromeClient() {
// 设置网页进度条
@Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
}
// 获取网页的标题
@Override
public void onReceivedTitle(WebView view, String title) {
super.onReceivedTitle(view, title);
}
// 获取JS弹窗时的信息
@Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
return true;
}
// 获取JS输入框的信息
@Override
public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
return super.onJsPrompt(view, url, message, defaultValue, result);
}
// 获取JS的确认框
@Override
public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
return super.onJsConfirm(view, url, message, result);
}
});
}
}