上篇介绍了一些WebView的设置,本篇为一些补充项。
首先加载HTML5的页面时,会出现页面空白的现象,原因是需要开启 DOM storage API 功能:
webSettings.setDomStorageEnabled(true);
其次,开发中需要注意的安全漏洞,详见《如何设计一个优雅健壮的Android WebView》:
@TargetApi(11)
private static final void removeJavascriptInterfaces(WebView webView) {
try {
if (Build.VERSION.SDK_INT >= 11 && Build.VERSION.SDK_INT < 17) {
webView.removeJavascriptInterface("searchBoxJavaBridge_");
webView.removeJavascriptInterface("accessibility");
webView.removeJavascriptInterface("accessibilityTraversal");
}
} catch (Throwable tr) {
tr.printStackTrace();
}
}
第三,其他需要注意的点:
- 需不需开启JS,以及是否允许文件访问、保存密码:
// Enable Javascript WebSettings webSettings = mWebView.getSettings(); webSettings.setJavaScriptEnabled(true); webSettings.setAllowFileAccess(false); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { webSettings.setAllowFileAccessFromFileURLs(false); } webSettings.setSavePassword(false);
- 缓存相关:
if (NetWorkDetector.isConnected(this.getActivity())) { // 根据cache-control决定是否从网络上取数据。 webSettings.setCacheMode(WebSettings.LOAD_DEFAULT); } else { // 没网,则从本地获取,即离线加载 webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); } // 开启 DOM storage API 功能 webSettings.setDomStorageEnabled(true); // 开启 database storage API 功能 webSettings.setDatabaseEnabled(true); // 开启 Application Caches 功能 webSettings.setAppCacheEnabled(true); // 设置 Application Caches 缓存目录 webSettings.setAppCachePath(this.getActivity().getDir("appcache", MODE_PRIVATE ).getPath());
-
5.1以上默认禁止了https和http混用,以下方式是开启
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW); }
- 在 Activity 销毁( WebView )的时候,先让 WebView 加载null内容,然后移除 WebView,再销毁 WebView,最后置空:
@Override protected void onDestroy() { if (mWebView != null) { mWebView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null); mWebView.clearHistory(); ((ViewGroup) mWebView.getParent()).removeView(mWebView); mWebView.destroy(); mWebView = null; } super.onDestroy(); } 作者:Carson_Ho 链接:https://www.jianshu.com/p/3c94ae673e2a 來源:简书 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。