javascript - Cordova Android 应用程序上的 Ajax 请求失败

标签 javascript android html cordova cordova-plugins

当我在 Chrome 浏览器上运行该项目时,ajax 请求工作正常,但当我在 Android 上安装该应用程序时,请求不再工作。 这是代码:

    var xhr=new XMLHttpRequest()
            xhr.onerror=function(){
           
                var message=alert(txt('Please turn on mobile data or Wi-Fi','Ligue os dados moveis ou Wi-Fi'))
                
            }
            
            xhr.onreadystatechange=function (){
                if (this.status== 200 && this.readyState == 4){ 
                alert("trye")
                  eval(xhr.responseText)
                
                } 
            }
            xhr.open("POST",`http://dpreaction.ml?i=js`)
            xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded')
            xhr.send()

config.xml 文件

<?xml version='1.0' encoding='utf-8'?>
<widget id="com.teste.teste" version="1.0.0" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <name>DP Reaction</name>
    <description>Inrease your things</description>
    <author email="<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="43242a2f2f362a302531222d202a30202c747303242e222a2f6d202c2e" rel="noreferrer noopener nofollow">[email protected]</a>" href="http://dpreaction.ml">
        DP Reaction
    </author>
    <content src="index.html" />
    <allow-intent href="*" />
    <access origin="*" />
    <allow-naviation href="*" />
</widget>

这是我的标签:

  <meta http-equiv="Content-Security-Policy" content="default-src * 'unsafe-inline' 'unsafe-eval'  data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *; img-src 'self' data: content:;">

最佳答案

根据https://github.com/apache/cordova-android/issues/1354 :

Content-Security-Policy 是一种与 CORS(跨源资源共享)不同的安全机制。

在 cordova-android@10 中,他们实现了一个 WebAssetLoader,它通过 https://localhost 协议(protocol)代理请求。 WebAssetLoader 的作用就像一个私有(private) Web 服务器,只能由您的应用程序访问。这样做是因为某些 Web View 功能要求您处于“安全上下文”(例如 HTTPS)中才能启用这些功能。这样做时,它确实启用了 CORS 强制执行。

Cordova android 9.x 使用普通的旧文件系统 (file://),它不强制执行 COR。这就是为什么您看到 XHR 请求在 9.x 中有效,但在 10.x 中无效。您可以通过启用 AndroidInsecureFileModeEnabled 使 10.x 表现得像 9.x

因此,如果您使用 cordova-android@10,只需在 config.xml 中添加以下首选项:

<preference name="AndroidInsecureFileModeEnabled" value="true" />

我也遇到了同样的问题,它为我解决了。 :)

关于javascript - Cordova Android 应用程序上的 Ajax 请求失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71066663/

相关文章:

javascript - 在 Web 应用程序中为分离的面板使用实际的浏览器窗口是否可行?

javascript - AngularJS 中的 lightGallery(jQuery 插件)

android - 制作一个列表查看选中的行

html - 段落对齐问题

javascript - 关闭浏览器窗口前调用 URL

javascript - XMLHttpRequest.open第三个参数false在iPad上不给出php mysql查询结果

android - 如果我只需要一个 webview,PhoneGap 是不是太多了?

android - RecyclerView 的第一项丢失

javascript - 如何在javascript中单击超链接时更改图像?

php - 如何使整个表格单元格充当可点击的表单区域