webview_flutter 解决在 Android 下 https 与 http 混用问题

811 阅读1分钟

混用 http 与 https 页面是会出现警告,如果在 https 站点下加载 http 静态资源也会失败

I/chromium( 8605): [INFO:CONSOLE(0)] "Mixed Content: The page at 'https://www.jizhuangx.com/myShopsList?storeId=11&my=1&companyType=1&brand=0' was loaded over HTTPS, but requested an insecure image 'http://cdn.ylnhome.com/shangcheng/165319044241689.jpg'. This request has been blocked; the content must be served over HTTPS.", source: https://www.jizhuangx.com/myShopsList?storeId=11&my=1&companyType=1&brand=0 (0)

webview_flutter 插件并没有提供修改 Android 层对于 Mixed 的配置项,如果目标是API级别26或更高,则必须首先在清单文件中启用它。

android:usesCleartextTraffic="true"

针对API级别21或更高版本时,需要修改对应包文件

flutterPlugins/webview_flutter_android-2.8.11/android/src/main/java/io/flutter/plugins/webviewflutter/WebSettingsHostApiImpl.java 

将代码

@Overridepublic 
void create(Long instanceId, Long webViewInstanceId) {
    final WebView webView = (WebView) instanceManager.getInstance(webViewInstanceId);  
    instanceManager.addInstance(webSettingsCreator.createWebSettings(webView), instanceId);
}

更改为:

@Overridepublic 
void create(Long instanceId, Long webViewInstanceId) {
    final WebView webView = (WebView) instanceManager.getInstance(webViewInstanceId);
    WebSettings webSettings = webSettingsCreator.createWebSettings(webView);
    webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
    instanceManager.addInstance(webSettings, instanceId);
}