You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从Cordova 10升级到11后Android WebView出现CORS问题求助

问题背景

我开发了一款Cordova应用,通过XMLHttpRequest向IoT设备发起HTTP请求获取数据(示例地址:http://192.168.1.1/file.xml)。将Cordova从10版本升级到11版本后,Android设备/WebView中的请求停止工作。

第一个错误及临时解决

通过chrome::inspect分析时,控制台出现混合内容错误:

Mixed Content: The page at 'https://localhost/index.html' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://192.168.1.1/file.xml'. This request has been blocked; the content must be served over HTTPS.

在config.xml中添加以下配置后解决了混合内容问题:

<preference name="Scheme" value="http" />

新出现的CORS错误

现在又出现CORS相关错误:

Access to XMLHttpRequest at 'http://192.168.1.1/file.xml' from origin 'http://localhost' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

解决思路
  • 配置Cordova访问白名单
    在config.xml里添加目标IoT设备的访问权限,这是Cordova官方推荐方式:

    <!-- 允许WebView导航到目标IoT设备地址 -->
    <allow-navigation href="http://192.168.1.1/*" />
    <!-- 允许向目标地址发起网络请求 -->
    <access origin="http://192.168.1.1/*" />
    

    如果IoT设备IP是同网段动态分配的,可用网段通配符:

    <allow-navigation href="http://192.168.*/*" />
    <access origin="http://192.168.*/*" />
    
  • 改用Cordova原生HTTP插件
    直接用原生插件绕开WebView的CORS限制,推荐cordova-plugin-advanced-http:
    先安装插件:

    cordova plugin add cordova-plugin-advanced-http
    

    替换原XMLHttpRequest请求代码:

    cordova.plugin.http.get('http://192.168.1.1/file.xml', {}, {}, function(response) {
        console.log(response.data); // 处理返回的XML数据
    }, function(error) {
        console.error(error);
    });
    
  • 修改Android WebView设置
    编辑Android平台主Activity文件(路径:platforms/android/app/src/main/java/[你的包名]/MainActivity.java),添加跨域配置:

    import android.webkit.WebSettings;
    import android.webkit.WebView;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 获取WebView实例
        WebView webView = (WebView) appView.getEngine().getView();
        WebSettings settings = webView.getSettings();
        // 允许跨域请求
        settings.setAllowUniversalAccessFromFileURLs(true);
        settings.setAllowFileAccessFromFileURLs(true);
    }
    

    注意:每次执行cordova prepare android可能会覆盖该文件,建议用Cordova钩子脚本自动注入配置。

  • 修改IoT设备响应头(若有权限)
    如果能修改IoT设备服务配置,添加CORS响应头允许http://localhost访问:

    Access-Control-Allow-Origin: http://localhost
    

    测试阶段可临时允许所有来源(生产环境不推荐):

    Access-Control-Allow-Origin: *
    

内容的提问来源于stack exchange,提问作者tk_

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 12:05:33