下面列出了android.webkit.WebSettings#setMixedContentMode ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@SuppressLint("SetJavaScriptEnabled")
@Override
protected void bindView() {
rlContent.setOnInsetsCallback(insets -> appBar.setPadding(0, insets.top, 0, 0));
refreshLayout.setOnRefreshListener(this);
WebSettings settings = webView.getSettings();
settings.setLoadWithOverviewMode(true);
settings.setUseWideViewPort(true);
settings.setUserAgentString(AnalyzeHeaders.getUserAgent(mConfig.getUserAgent()));
settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
settings.setJavaScriptEnabled(true);
settings.setDomStorageEnabled(true);
settings.setSupportZoom(true);
settings.setBuiltInZoomControls(true);
settings.setDisplayZoomControls(false);
settings.setJavaScriptCanOpenWindowsAutomatically(false);
}
/**
* 默认webview设置
* @param settings
*/
private void initSetting(WebSettings settings, Context context){
//5.0以上开启混合模式加载
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
}
settings.setLoadWithOverviewMode(true);
settings.setUseWideViewPort(true);
//允许js代码 在Android 4.3版本调用WebSettings.setJavaScriptEnabled()方法时会调用一下reload方法,同时会回调多次WebChromeClient.onJsPrompt()
settings.setJavaScriptEnabled(true);
//允许SessionStorage/LocalStorage存储
settings.setDomStorageEnabled(true);
//禁用放缩
settings.setDisplayZoomControls(false);
settings.setBuiltInZoomControls(false);
//禁用文字缩放
settings.setTextZoom(100);
//10M缓存,api 18后,系统自动管理。
settings.setAppCacheMaxSize(10 * 1024 * 1024);
//允许缓存,设置缓存位置 缓存位置由用户指定
settings.setAppCacheEnabled(true);
settings.setAppCachePath(context.getDir("appcache", 0).getPath());
//允许WebView使用File协议
settings.setAllowFileAccess(true);
//不保存密码
settings.setSavePassword(false);
//自动加载图片
settings.setLoadsImagesAutomatically(true);
}
@TargetApi(16)
@SuppressLint("SetJavaScriptEnabled")
protected void setupWebSettings(WebSettings ws) {
ws.setAppCacheEnabled(true);
WebViewCompatUtils.enableJavaScriptForWebView(getContext(), ws);
ws.setJavaScriptEnabled(true);
ws.setGeolocationEnabled(true);
ws.setBuiltInZoomControls(true);
ws.setDisplayZoomControls(false);
ws.setAllowFileAccess(true);
if (Utils.hasJellyBean()) {
ws.setAllowFileAccessFromFileURLs(true);
ws.setAllowUniversalAccessFromFileURLs(true);
}
// enable html cache
ws.setDomStorageEnabled(true);
ws.setAppCacheEnabled(true);
// Set cache size to 8 mb by default. should be more than enough
ws.setAppCacheMaxSize(1024 * 1024 * 8);
// This next one is crazy. It's the DEFAULT location for your app's cache
// But it didn't work for me without this line
ws.setAppCachePath("/data/data/" + getContext().getPackageName() + "/cache");
ws.setAllowFileAccess(true);
ws.setCacheMode(WebSettings.LOAD_DEFAULT);
String ua = ws.getUserAgentString() + " " + Rexxar.getUserAgent();
ws.setUserAgentString(ua);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
ws.setUseWideViewPort(true);
}
if (Utils.hasLollipop()) {
ws.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
}
}
@SuppressLint("SetJavaScriptEnabled")
private void handleSetting() {
WebSettings ws = mWebView.getSettings();
// 保存表单数据
ws.setSaveFormData(true);
// 是否应该支持使用其屏幕缩放控件和手势缩放
ws.setSupportZoom(true);
ws.setBuiltInZoomControls(true);
ws.setDisplayZoomControls(false);
// 启动应用缓存
ws.setAppCacheEnabled(true);
// 设置缓存模式
ws.setCacheMode(WebSettings.LOAD_DEFAULT);
// setDefaultZoom api19被弃用
// 网页内容的宽度自适应屏幕
ws.setLoadWithOverviewMode(true);
ws.setUseWideViewPort(true);
// 告诉WebView启用JavaScript执行。默认的是false。
ws.setJavaScriptEnabled(true);
// 页面加载好以后,再放开图片
ws.setBlockNetworkImage(false);
// 使用localStorage则必须打开
ws.setDomStorageEnabled(true);
// 排版适应屏幕
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
ws.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
} else {
ws.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
}
// WebView是否新窗口打开(加了后可能打不开网页)
// ws.setSupportMultipleWindows(true);
// webview从5.0开始默认不允许混合模式,https中不能加载http资源,需要设置开启。
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
ws.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
}
/** 设置字体默认缩放大小(改变网页字体大小,setTextSize api14被弃用)*/
ws.setTextZoom(100);
}
@SuppressWarnings("static-method")
@SuppressLint("NewApi")
protected void setMixedContentAllowed(final WebSettings webSettings, final boolean allowed) {
if (Build.VERSION.SDK_INT >= 21) {
webSettings.setMixedContentMode(allowed ? WebSettings.MIXED_CONTENT_ALWAYS_ALLOW : WebSettings.MIXED_CONTENT_NEVER_ALLOW);
}
}
@SuppressLint({"SetJavaScriptEnabled", "JavascriptInterface"})
private static WebView createAjaxWebView(AjaxParams params, Handler handler) {
WebView webView = new WebView(params.context.getApplicationContext());
WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setDomStorageEnabled(true);
settings.setBlockNetworkImage(true);
settings .setMediaPlaybackRequiresUserGesture(false);
settings.setUserAgentString(params.getUserAgent());
settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
if (params.isSniff()) {
webView.setWebViewClient(new SnifferWebClient(params, handler));
} else {
webView.setWebViewClient(new HtmlWebViewClient(handler));
webView.addJavascriptInterface(new JavaInjectMethod(handler), "OUTHTML");
}
switch (params.getRequestMethod()) {
case POST:
webView.postUrl(params.url, params.postData);
break;
case GET:
case DEFAULT:
webView.loadUrl(params.url, params.headerMap);
break;
}
return webView;
}
private void initWebView() {
WebSettings ws = webView.getSettings();
//网页内容的宽度是否可以大于WebView控件的宽度
ws.setLoadWithOverviewMode(false);
//保存表单数据
ws.setSaveFormData(true);
//是否应该支持使用其屏幕缩放控件和手势缩放
ws.setSupportZoom(true);
ws.setBuiltInZoomControls(true);
ws.setDisplayZoomControls(false);
//启动应用缓存
ws.setAppCacheEnabled(true);
//设置缓存模式
ws.setCacheMode(WebSettings.LOAD_DEFAULT);
//启用JavaScript执行,默认的是false
ws.setJavaScriptEnabled(true);
//页面加载后之后再放开图片
ws.setBlockNetworkImage(false);
//使用localStorage则必须打开
ws.setDomStorageEnabled(true);
//设置文字的格式
ws.setDefaultTextEncodingName("UTF-8");
//WebView5.0开始默认不允许混合模式,https中不能加载http资源,需要设置开启
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
ws.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
}
//设置字体默认缩放大小(改变网页字体大小,setTextSize API14被弃用)
ws.setTextZoom(100);
webView.setWebChromeClient(new MyWebChromeClient(this));
webView.setWebViewClient(new MyWebViewClient(this));
webView.addJavascriptInterface(new ImageClickInterface(this), "injectedObject");
}
/**
* Initialize the WebView, setting required flags
*/
private void initWebView() {
WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setDomStorageEnabled(true);
settings.setGeolocationEnabled(true);
settings.setDatabaseEnabled(true);
settings.setAppCacheEnabled(true);
settings.setMediaPlaybackRequiresUserGesture(false);
settings.setJavaScriptCanOpenWindowsAutomatically(true);
if (Config.getBoolean("android.allowMixedContent", false)) {
settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
}
String backgroundColor = Config.getString("android.backgroundColor" , Config.getString("backgroundColor", null));
try {
if (backgroundColor != null) {
webView.setBackgroundColor(Color.parseColor(backgroundColor));
}
} catch (IllegalArgumentException ex) {
Log.d(LogUtils.getCoreTag(), "WebView background color not applied");
}
boolean defaultDebuggable = false;
if (isDevMode()) {
defaultDebuggable = true;
}
WebView.setWebContentsDebuggingEnabled(Config.getBoolean("android.webContentsDebuggingEnabled", defaultDebuggable));
}
@SuppressLint({"SetJavaScriptEnabled"})
public void initializeSettings(){
boolean isTablet = getResources().getBoolean(R.bool.isTablet);
String lang = Locale.getDefault().getDisplayLanguage();
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
cookieManager.setAcceptThirdPartyCookies(NestedWebview.this, true);
WebSettings mWebSettings = getSettings();
mWebSettings.setJavaScriptEnabled(true);
mWebSettings.setJavaScriptCanOpenWindowsAutomatically(true);
mWebSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
mWebSettings.setBuiltInZoomControls(true);
mWebSettings.setDisplayZoomControls(false);
mWebSettings.setMediaPlaybackRequiresUserGesture(false);
if(isTablet){
mWebSettings.setUserAgentString("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Simplicity/57.0.3098.116");
mWebSettings.setLoadWithOverviewMode(true);
mWebSettings.setUseWideViewPort(true);
}else{
mWebSettings.setUserAgentString(null);
mWebSettings.setLoadWithOverviewMode(true);
mWebSettings.setUseWideViewPort(true);
}
mWebSettings.setAppCacheEnabled(true);
mWebSettings.setDatabaseEnabled(true);
if (UserPreferences.getBoolean("enable_location", false)) {
mWebSettings.setGeolocationEnabled(true);
} else {
mWebSettings.setGeolocationEnabled(false);
}
if(UserPreferences.getBoolean("lite_mode", false)){
mWebSettings.setLoadsImagesAutomatically(false);
}else{
mWebSettings.setLoadsImagesAutomatically(true);
}
mWebSettings.setAllowFileAccessFromFileURLs(true);
mWebSettings.setAllowUniversalAccessFromFileURLs(true);
mWebSettings.setDomStorageEnabled(true);
mWebSettings.setTextZoom(Integer.parseInt(UserPreferences.getInstance(WEB_ACTIVITY).getFont()));
addJavascriptInterface(new ReaderHandler(SimplicityApplication.getContextOfApplication(), MainActivity.getMainActivity()), "simplicity_reader");
if(UserPreferences.getBoolean("facebook_photos", false)){
addJavascriptInterface(new ImageInterface(WEB_ACTIVITY), "Photos");
}
}
@SuppressLint("JavascriptInterface")
private void initWebView() {
WebSettings ws = mWebView.getSettings();
// 网页内容的宽度是否可大于WebView控件的宽度
ws.setLoadWithOverviewMode(false);
// 保存表单数据
ws.setSaveFormData(true);
// 是否应该支持使用其屏幕缩放控件和手势缩放
ws.setSupportZoom(true);
ws.setBuiltInZoomControls(true);
ws.setDisplayZoomControls(false);
// 启动应用缓存
ws.setAppCacheEnabled(true);
// 设置缓存模式
ws.setCacheMode(WebSettings.LOAD_DEFAULT);
// setDefaultZoom api19被弃用
// 设置此属性,可任意比例缩放。
ws.setUseWideViewPort(true);
// 缩放比例 1
mWebView.setInitialScale(1);
// 告诉WebView启用JavaScript执行。默认的是false。
ws.setJavaScriptEnabled(true);
//如果启用了JavaScript,要做好安全措施,防止远程执行漏洞
removeJavascriptInterfaces(mWebView);
// 页面加载好以后,再放开图片
ws.setBlockNetworkImage(false);
// 使用localStorage则必须打开
ws.setDomStorageEnabled(true);
//自动加载图片
ws.setLoadsImagesAutomatically(true);
// 排版适应屏幕
ws.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
// WebView是否支持多个窗口。
ws.setSupportMultipleWindows(true);
// webView从5.0开始默认不允许混合模式,https中不能加载http资源,需要设置开启。
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
ws.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
}
/*设置字体默认缩放大小(改变网页字体大小,setTextSize api14被弃用)*/
ws.setTextZoom(100);
//在js中调用本地java方法
jsAppInterface = new JsAppInterface(this, mWebView);
jsAppInterface.register();
mWebView.addJavascriptInterface(jsAppInterface, "WebViewJsMethodName");
mWebView.addJavascriptInterface(new JavascriptInterface(this), "injectedObject");
mWebView.setWebViewClient(new MyWebViewClient());
mWebView.setWebChromeClient(webChromeClient = new MyWebChromeClient());
mWebView.setScrollWebListener(new ScrollWebView.OnScrollWebListener() {
@Override
public void onScroll(int dx, int dy) {
//WebView的总高度
float webViewContentHeight = mWebView.getContentHeight() * mWebView.getScale();
//WebView的现高度
float webViewCurrentHeight = (mWebView.getHeight() + mWebView.getScrollY());
LogUtils.e("webViewContentHeight=" + webViewContentHeight);
LogUtils.e("webViewCurrentHeight=" + webViewCurrentHeight);
if ((webViewContentHeight - webViewCurrentHeight) == 0) {
LogUtils.e("WebView滑动到了底端");
}
}
});
}
private void initWebView() {
mProgressBar.setVisibility(View.VISIBLE);
WebSettings ws = webView.getSettings();
// 网页内容的宽度是否可大于WebView控件的宽度
ws.setLoadWithOverviewMode(false);
// 保存表单数据
ws.setSaveFormData(true);
// 是否应该支持使用其屏幕缩放控件和手势缩放
ws.setSupportZoom(true);
ws.setBuiltInZoomControls(true);
ws.setDisplayZoomControls(false);
// 启动应用缓存
ws.setAppCacheEnabled(true);
// 设置缓存模式
ws.setCacheMode(WebSettings.LOAD_DEFAULT);
// setDefaultZoom api19被弃用
// 设置此属性,可任意比例缩放。
ws.setUseWideViewPort(true);
// 缩放比例 1
webView.setInitialScale(1);
// 告诉WebView启用JavaScript执行。默认的是false。
ws.setJavaScriptEnabled(true);
// 页面加载好以后,再放开图片
ws.setBlockNetworkImage(false);
// 使用localStorage则必须打开
ws.setDomStorageEnabled(true);
// 排版适应屏幕
ws.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
// WebView是否支持多个窗口。
ws.setSupportMultipleWindows(true);
// webview从5.0开始默认不允许混合模式,https中不能加载http资源,需要设置开启。
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
ws.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
}
/** 设置字体默认缩放大小(改变网页字体大小,setTextSize api14被弃用)*/
ws.setTextZoom(100);
mWebChromeClient = new MyWebChromeClient(this);
webView.setWebChromeClient(mWebChromeClient);
// 与js交互
webView.addJavascriptInterface(new ImageClickInterface(this), "injectedObject");
webView.setWebViewClient(new MyWebViewClient(this));
}
private void init(Context context) {
if (!(context instanceof Activity)) {
throw new RuntimeException("only support Activity context");
} else {
this.mContainerActivity = (Activity) context;
WebSettings webSettings = this.getSettings();
webSettings.setPluginState(WebSettings.PluginState.ON);
webSettings.setJavaScriptEnabled(true);
webSettings.setAllowFileAccess(false);
webSettings.setLoadsImagesAutomatically(true);
webSettings.setUseWideViewPort(true);
webSettings.setBuiltInZoomControls(false);
webSettings.setDefaultTextEncodingName("UTF-8");
webSettings.setDomStorageEnabled(true);
webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
webSettings.setJavaScriptCanOpenWindowsAutomatically(false);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) {
webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
setWebContentsDebuggingEnabled(true);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
webSettings.setMixedContentMode(0);
}
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.GINGERBREAD_MR1 && Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
this.removeJavascriptInterface("searchBoxJavaBridge_");
this.removeJavascriptInterface("accessibilityTraversal");
this.removeJavascriptInterface("accessibility");
}
mMyWebViewClient = new MyWebViewClient();
this.setWebViewClient(mMyWebViewClient);
this.setWebChromeClient(new WebChromeClient() {
@Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
if (newProgress < 100) {
showLoadProgress(newProgress);
} else {
hideLoadProgress();
}
}
});
addProgressView();
}
}
@SuppressLint("SetJavaScriptEnabled")
private void initWebSettings() {
WebSettings settings = sMm.getSettings();
settings.setUserAgentString("" + SPUtils.get(MainActivity.this, "if_7", ""));//UA
//支持获取手势焦点
sMm.requestFocusFromTouch();
//支持JS
settings.setJavaScriptEnabled((Boolean) SPUtils.get(MainActivity.this, "if_1", true));
//支持插件
// settings.setPluginState(WebSettings.PluginState.ON);
//设置适应屏幕
settings.setUseWideViewPort(true);
settings.setLoadWithOverviewMode(true);
//支持缩放
settings.setSupportZoom((Boolean) SPUtils.get(MainActivity.this, "if_3", false)); // 支持缩放
//隐藏原生的缩放控件
settings.setDisplayZoomControls(false);
//支持内容重新布局
settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
settings.supportMultipleWindows();
settings.setSupportMultipleWindows(false);
//设置缓存模式
settings.setGeolocationEnabled((Boolean) SPUtils.get(MainActivity.this, "if_2", true));//允许地理位置可用
settings.setDomStorageEnabled(true);
settings.setDatabaseEnabled((Boolean) SPUtils.get(MainActivity.this, "if_4", true));
settings.setCacheMode(WebSettings.LOAD_DEFAULT);
settings.setAppCacheEnabled(true);
settings.setAppCachePath(sMm.getContext().getCacheDir().getAbsolutePath());
//settings.setRenderPriority(WebSettings.RenderPriority.HIGH); //提高渲染的优先级
//设置可访问文件
settings.setAllowFileAccess(true);
//当webview调用requestFocus时为webview设置节点
settings.setNeedInitialFocus(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
}
settings.setLoadsImagesAutomatically(false);
// settings.setNeedInitialFocus(true);
//设置编码格式
//settings.setDefaultTextEncodingName("UTF-8");
}
@SuppressLint({"SetJavaScriptEnabled", "AddJavascriptInterface"})
private void initWebView() {
WebSettings ws = webView.getSettings();
// 保存表单数据
ws.setSaveFormData(true);
// 是否应该支持使用其屏幕缩放控件和手势缩放
ws.setSupportZoom(true);
ws.setBuiltInZoomControls(true);
ws.setDisplayZoomControls(false);
// 启动应用缓存
ws.setAppCacheEnabled(true);
// 设置缓存模式
ws.setCacheMode(WebSettings.LOAD_DEFAULT);
// setDefaultZoom api19被弃用
// 网页内容的宽度自适应屏幕
ws.setLoadWithOverviewMode(true);
ws.setUseWideViewPort(true);
// 网页缩放至100,一般的网页达到屏幕宽度效果,个别除外
// webView.setInitialScale(100);
// 关掉下滑弧形阴影
// webView.setOverScrollMode(WebView.OVER_SCROLL_NEVER);
// 告诉WebView启用JavaScript执行。默认的是false。
ws.setJavaScriptEnabled(true);
// 页面加载好以后,再放开图片
ws.setBlockNetworkImage(false);
// 使用localStorage则必须打开
ws.setDomStorageEnabled(true);
// 排版适应屏幕
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
ws.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
} else {
ws.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
}
// WebView是否新窗口打开(加了后可能打不开网页)
// ws.setSupportMultipleWindows(true);
// webview从5.0开始默认不允许混合模式,https中不能加载http资源,需要设置开启。
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
ws.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
}
/** 设置字体默认缩放大小(改变网页字体大小,setTextSize api14被弃用)*/
ws.setTextZoom(100);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
webView.setScrollBarSize(WebTools.dp2px(this, 3));
}
mWebChromeClient = new MyWebChromeClient(this);
webView.setWebChromeClient(mWebChromeClient);
// 与js交互
webView.addJavascriptInterface(new MyJavascriptInterface(this), "injectedObject");
webView.setWebViewClient(new MyWebViewClient(this));
webView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return handleLongImage();
}
});
}
private void initWebView() {
mProgressBar.setVisibility(View.VISIBLE);
WebSettings ws = webView.getSettings();
// 网页内容的宽度是否可大于WebView控件的宽度
ws.setLoadWithOverviewMode(false);
// 保存表单数据
ws.setSaveFormData(true);
// 是否应该支持使用其屏幕缩放控件和手势缩放
ws.setSupportZoom(true);
ws.setBuiltInZoomControls(true);
ws.setDisplayZoomControls(false);
// 启动应用缓存
ws.setAppCacheEnabled(true);
// 设置缓存模式
ws.setCacheMode(WebSettings.LOAD_DEFAULT);
// setDefaultZoom api19被弃用
// 设置此属性,可任意比例缩放。
ws.setUseWideViewPort(true);
// 不缩放
webView.setInitialScale(100);
// 告诉WebView启用JavaScript执行。默认的是false。
ws.setJavaScriptEnabled(true);
// 页面加载好以后,再放开图片
ws.setBlockNetworkImage(false);
// 使用localStorage则必须打开
ws.setDomStorageEnabled(true);
// 排版适应屏幕
ws.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
// WebView是否新窗口打开(加了后可能打不开网页)
// ws.setSupportMultipleWindows(true);
// webview从5.0开始默认不允许混合模式,https中不能加载http资源,需要设置开启。
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
ws.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
}
/** 设置字体默认缩放大小(改变网页字体大小,setTextSize api14被弃用)*/
ws.setTextZoom(100);
mWebChromeClient = new MyWebChromeClient(this);
webView.setWebChromeClient(mWebChromeClient);
// 与js交互
webView.addJavascriptInterface(new MyJavascriptInterface(this), "injectedObject");
webView.setWebViewClient(new MyWebViewClient(this));
webView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return handleLongImage();
}
});
}
private void initWebSettings() {
WebSettings webSettings = mBaseWebView.getSettings();
if (webSettings == null) return;
//设置字体缩放倍数,默认100
webSettings.setTextZoom(100);
// 支持 Js 使用
webSettings.setJavaScriptEnabled(true);
// 开启DOM缓存
webSettings.setDomStorageEnabled(true);
// 开启数据库缓存
webSettings.setDatabaseEnabled(true);
// 支持自动加载图片
webSettings.setLoadsImagesAutomatically(hasKitkat());
if (isCache) {
// 设置 WebView 的缓存模式
webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
// 支持启用缓存模式
webSettings.setAppCacheEnabled(true);
// 设置 AppCache 最大缓存值(现在官方已经不提倡使用,已废弃)
webSettings.setAppCacheMaxSize(8 * 1024 * 1024);
// Android 私有缓存存储,如果你不调用setAppCachePath方法,WebView将不会产生这个目录
webSettings.setAppCachePath(mContext.getCacheDir().getAbsolutePath());
}
// 数据库路径
if (!hasKitkat()) {
webSettings.setDatabasePath(mContext.getDatabasePath("html").getPath());
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
}
// 关闭密码保存提醒功能
webSettings.setSavePassword(false);
// 支持缩放
webSettings.setSupportZoom(true);
// 设置 UserAgent 属性
webSettings.setUserAgentString("");
// 允许加载本地 html 文件/false
webSettings.setAllowFileAccess(true);
// 允许通过 file url 加载的 Javascript 读取其他的本地文件,Android 4.1 之前默认是true,在 Android 4.1 及以后默认是false,也就是禁止
webSettings.setAllowFileAccessFromFileURLs(false);
// 允许通过 file url 加载的 Javascript 可以访问其他的源,包括其他的文件和 http,https 等其他的源,
// Android 4.1 之前默认是true,在 Android 4.1 及以后默认是false,也就是禁止
// 如果此设置是允许,则 setAllowFileAccessFromFileURLs 不起做用
webSettings.setAllowUniversalAccessFromFileURLs(false);
}
@SuppressWarnings("deprecation")
@SuppressLint({ "SetJavaScriptEnabled", "NewApi" })
public void initializeSettings(WebSettings settings, Context context) {
//setPageCacheCapacity2(settings);
if (API < 18) {
settings.setAppCacheMaxSize(Long.MAX_VALUE);
}
if (API < 17) {
settings.setEnableSmoothTransition(true);
}
if (API > 16) {
settings.setMediaPlaybackRequiresUserGesture(true);
}
if (API >= Build.VERSION_CODES.LOLLIPOP && !mBrowserController.isIncognito()) {
settings.setMixedContentMode(WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
} else if (API >= Build.VERSION_CODES.LOLLIPOP) {
// We're in Incognito mode, reject
settings.setMixedContentMode(WebSettings.MIXED_CONTENT_NEVER_ALLOW);
}
settings.setDomStorageEnabled(true);
settings.setAppCacheEnabled(true);
settings.setCacheMode(WebSettings.LOAD_DEFAULT);
settings.setDatabaseEnabled(true);
settings.setSupportZoom(true);
settings.setBuiltInZoomControls(true);
settings.setDisplayZoomControls(false);
settings.setAllowContentAccess(true);
settings.setAllowFileAccess(true);
settings.setDefaultTextEncodingName("utf-8");
if (API > 16) {
settings.setAllowFileAccessFromFileURLs(false);
settings.setAllowUniversalAccessFromFileURLs(false);
}
settings.setAppCachePath(context.getDir("appcache", 0).getPath());
settings.setGeolocationDatabasePath(context.getDir("geolocation", 0).getPath());
if (API < Build.VERSION_CODES.KITKAT) {
settings.setDatabasePath(context.getDir("databases", 0).getPath());
}
}
public WebView(Context context) {
super(context);
WebSettings settings = getSettings();
if(Build.VERSION.SDK_INT >= 16) {
settings.setAllowFileAccessFromFileURLs(true);
settings.setAllowUniversalAccessFromFileURLs(true);
}
if (Build.VERSION.SDK_INT >= 19) {
try {
_evaluateJavascript = android.webkit.WebView.class.getMethod("evaluateJavascript", String.class, ValueCallback.class);
} catch(NoSuchMethodException e) {
DeviceLog.exception("Method evaluateJavascript not found", e);
_evaluateJavascript = null;
}
}
settings.setAppCacheEnabled(false);
settings.setBlockNetworkImage(false);
settings.setBlockNetworkLoads(false);
settings.setBuiltInZoomControls(false);
settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
settings.setDatabaseEnabled(false);
if(Build.VERSION.SDK_INT >= 11) {
settings.setDisplayZoomControls(false);
}
settings.setDomStorageEnabled(false);
if(Build.VERSION.SDK_INT >= 11) {
settings.setEnableSmoothTransition(false);
}
settings.setGeolocationEnabled(false);
settings.setJavaScriptCanOpenWindowsAutomatically(false);
settings.setJavaScriptEnabled(true);
settings.setLightTouchEnabled(false);
settings.setLoadWithOverviewMode(false);
settings.setLoadsImagesAutomatically(true);
if(Build.VERSION.SDK_INT >= 17) {
settings.setMediaPlaybackRequiresUserGesture(false);
}
if(Build.VERSION.SDK_INT >= 21) {
settings.setMixedContentMode(WebSettings.MIXED_CONTENT_NEVER_ALLOW);
}
settings.setNeedInitialFocus(true);
settings.setPluginState(WebSettings.PluginState.OFF);
settings.setRenderPriority(WebSettings.RenderPriority.NORMAL);
settings.setSaveFormData(false);
settings.setSavePassword(false);
settings.setSupportMultipleWindows(false);
settings.setSupportZoom(false);
settings.setUseWideViewPort(true);
setHorizontalScrollBarEnabled(false);
setVerticalScrollBarEnabled(false);
setInitialScale(0);
setBackgroundColor(Color.TRANSPARENT);
ViewUtilities.setBackground(this, new ColorDrawable(Color.TRANSPARENT));
setBackgroundResource(0);
addJavascriptInterface(new WebViewBridgeInterface(), "webviewbridge");
}
void updateFromPreferences(SharedPreferences prefs) {
String theme = prefs.getString(Constants.PREF_THEME, "dark");
mDarkTheme = "dark".equals(theme);
mImmersive = prefs.getBoolean(Constants.PREF_IMMERSIVE, false);
mTrackBrowserConnection = prefs.getBoolean(Constants.PREF_TRACK_BROWSER_CONNECTION, false);
mLogBrowserMsg = prefs.getBoolean(Constants.PREF_LOG_BROWSER_MESSAGES, false);
mAllowWebRTC = prefs.getBoolean(Constants.PREF_ALLOW_WEBRTC, false);
boolean isDesktop = prefs.getBoolean(Constants.PREF_DESKTOP_MODE, false);
boolean isJavascript = prefs.getBoolean(Constants.PREF_JAVASCRIPT, false);
boolean isAutoplay = prefs.getBoolean(Constants.PREF_AUTOPLAY_VIDEO, false);
boolean cacheDeactivated = prefs.getBoolean(Constants.PREF_DISABLE_CACHE, false);
mDraggingPrevented = prefs.getBoolean(Constants.PREF_PREVENT_DRAGGING, false);
WebSettings webSettings = getSettings();
webSettings.setUseWideViewPort(isDesktop);
webSettings.setLoadWithOverviewMode(isDesktop);
webSettings.setJavaScriptEnabled(isJavascript);
webSettings.setCacheMode(cacheDeactivated ? WebSettings.LOAD_NO_CACHE : WebSettings.LOAD_DEFAULT);
webSettings.setMediaPlaybackRequiresUserGesture(!isAutoplay);
boolean loadStartUrl = false;
boolean reloadUrl = false;
if (mStartPage == null || !mStartPage.equalsIgnoreCase(prefs.getString(Constants.PREF_START_URL, ""))) {
mStartPage = prefs.getString(Constants.PREF_START_URL, "");
loadStartUrl = true;
}
loadStartUrl = loadStartUrl || isShowingErrorPage();
if (mServerURL == null || !mServerURL.equalsIgnoreCase(prefs.getString(Constants.PREF_SERVER_URL, "!$%"))) {
mServerURL = prefs.getString(Constants.PREF_SERVER_URL, "");
loadStartUrl = loadStartUrl || mStartPage == null || mStartPage.isEmpty();
}
if (mAllowMixedContent != prefs.getBoolean(Constants.PREF_ALLOW_MIXED_CONTENT, false)) {
mAllowMixedContent = !mAllowMixedContent;
reloadUrl = true;
}
if (mHwAccelerated != prefs.getBoolean(Constants.PREF_HW_ACCELERATED, false)) {
mHwAccelerated = !mHwAccelerated;
if (mHwAccelerated) {
setLayerType(LAYER_TYPE_HARDWARE, null);
} else {
setLayerType(LAYER_TYPE_SOFTWARE, null);
}
}
webSettings.setMixedContentMode(mAllowMixedContent ? WebSettings.MIXED_CONTENT_ALWAYS_ALLOW : WebSettings.MIXED_CONTENT_NEVER_ALLOW);
if (mNetworkTracker.isConnected()) {
if (loadStartUrl) {
loadStartUrl();
} else if (reloadUrl) {
reload();
}
} else {
showHtml(getContext().getString(R.string.waitingNetwork),
getContext().getString(R.string.notConnectedReloadPendingHTML));
}
}
/**
* @param aWebView
* **/
public static void setupWebViewAttributes(KCWebView aWebView)
{
try
{
WebSettings webSettings = aWebView.getSettings();
setCustomizedUA(webSettings);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
{
webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
}
webSettings.setJavaScriptEnabled(true);
webSettings.setLoadWithOverviewMode(true);
webSettings.setUseWideViewPort(true);
webSettings.setBuiltInZoomControls(false);
webSettings.setSupportZoom(true);
webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
webSettings.setAppCachePath(aWebView.getWebPath().getRootPath() + "/webcache");
webSettings.setAppCacheEnabled(true);
// webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
webSettings.setLoadsImagesAutomatically(true);
webSettings.setLightTouchEnabled(false);
webSettings.setDomStorageEnabled(true); // supports local storage
webSettings.setDatabaseEnabled(true); // supports local storage
webSettings.setDatabasePath(aWebView.getWebPath().getRootPath() + "/localstorage");
// we are using ApplicationContext when creaing KCWebView, without disabling the "Save Password" dialog
// there will be an exception that would cause crash: "Unable to add window -- token null is not for an application"
webSettings.setSavePassword(false);
aWebView.setHorizontalScrollBarEnabled(false);
// mWebView.setVerticalScrollBarEnabled(false);
aWebView.setScrollbarFadingEnabled(true);
aWebView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
}
catch (Exception e)
{
KCLog.e(e);
}
}