React Native安卓发布版WebView无法加载静态服务器文件问题
问题根因及解决方案
核心原因
- 安卓正式包默认启用明文HTTP流量限制:安卓9(API 28)及以上系统默认禁止所有明文HTTP请求,开发版因为Debug配置默认放开了该限制,所以运行正常,正式包未做特殊配置时会拦截WebView发往本地静态服务器的HTTP请求
- WebView默认安全策略限制:正式包构建时WebView会默认启用更严格的混合内容校验,禁止本地上下文加载非授信的HTTP资源
- 你已经确认设备浏览器可直接访问静态服务器资源,可排除静态服务器本身配置、资源打包丢失、混淆裁剪的问题,问题完全出在WebView的访问限制上
修复步骤
1. 放开本地明文流量限制
在android/app/src/main/res/xml目录下新建network_security_config.xml文件,添加如下配置:
<?xml version="1.0" encoding="utf-8"?> <network-security-config> <domain-config cleartextTrafficPermitted="true"> <domain includeSubdomains="false">localhost</domain> <domain includeSubdomains="false">127.0.0.1</domain> </domain-config> </network-security-config>
然后在AndroidManifest.xml的application标签中添加属性关联该配置:
<application ... android:networkSecurityConfig="@xml/network_security_config" ...>
2. 调整WebView安全配置
给WebView组件添加如下属性,关闭严格混合内容校验:
<WebView ... mixedContentMode="always" allowFileAccess={true} allowContentAccess={true} ... />
内容的提问来源于stack exchange,提问作者shawn
相关产品推荐
相关产品推荐

