WebView初始化设置
//设置javaScript
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT); //设置 缓存模式
// 开启 DOM storage API 功能
webView.getSettings().setDomStorageEnabled(true);
//开启 database storage API 功能
webView.getSettings().setDatabaseEnabled(true);
设置缓存路径
String cacheDirPath = getFilesDir().getAbsolutePath() + APP_CACAHE_DIRNAME;
//设置数据库缓存路径
webView.getSettings().setDatabasePath(cacheDirPath);
//设置 Application Caches 缓存目录
webView.getSettings().setAppCachePath(cacheDirPath);
//开启 Application Caches 功能
webView.getSettings().setAppCacheEnabled(true);
设置UserAgent
webView.getSettings().setUserAgentString();
WebView加载url
webView.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
//每次加载url前都同步cookie
synCookies(url);
//加载url
view.loadUrl(url);
return true;
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
//这里可以展示加载界面
showLoading();
super.onPageStarted(view, url, favicon);
}
@Override
public void onPageFinished(WebView view, String url) {
cookies = cookieManager.getCookie(url);
//隐藏加载界面
hideLoading();
super.onPageFinished(view, url);
}
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
}
@Override
public void onFormResubmission(WebView view, Message dontResend, Message resend) {
resend.sendToTarget();
}
});
WebView加载首页url
//同步首页url的cookie
synCookies(url);
//加载首页url
webView.loadUrl(url);
同步cookie
private void synCookies(String url) {
String cookie = cookieManager.getCookie(url);
//保存最新cookie到本地。
if (cookie != null ) {
getSP().edit().putString(SP_COOKIE, cookie).commit();
}
//将本地cookie设置到该url中
if (getSP().getString(WebAcitivity.SP_COOKIE, null) != null) {
String cookies = getSP().getString(WebAcitivity.SP_COOKIE, null);
String[] cook = cookies.split(";");
for (int i = 0; i < cook.length; i++) {
cookieManager.setCookie(url, cook[i]);
}
}
}
WebView与JS交互
webView.setWebChromeClient(new WebChromeClient() {
@Override
public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
return super.onJsConfirm(view, url, message, result);
}
@Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
return super.onJsAlert(view, url, message, result);
}
@Override
public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
//TODO 这里收到message和defaultValue
//注意:这里的回调在子线程中,需要使用handler在主线程中实现业务逻辑
result.cancel();
return true;
}
});
网友评论