上篇介绍了一些WebView的设置,本篇为一些补充项。html
首先加载HTML5的页面时,会出现页面空白的现象,缘由是须要开启 DOM storage API 功能:java
webSettings.setDomStorageEnabled(true);
其次,开发中须要注意的安全漏洞,详见《如何设计一个优雅健壮的Android WebView》:web
@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(); } }
第三,其余须要注意的点:缓存
// 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); }
@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 來源:简书 著做权归做者全部。商业转载请联系做者得到受权,非商业转载请注明出处。