Gilluisf
Gilluisf

Reputation: 41

Ajax requests are failing on Cordova Android app

When I ran the project on Chrome browser the ajax requests worked fine but when I installed the app on Android the requests are not working anymore. This is the code:

    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()

the config.xml file

<?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="[email protected]" href="http://dpreaction.ml">
        DP Reaction
    </author>
    <content src="index.html" />
    <allow-intent href="*" />
    <access origin="*" />
    <allow-naviation href="*" />
</widget>

And this is my tag:

  <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:;">

Upvotes: 2

Views: 920

Answers (1)

saleem
saleem

Reputation: 415

According to https://github.com/apache/cordova-android/issues/1354:

Content-Security-Policy is a different security mechanism than CORS (Cross-Origin Resource Sharing).

In cordova-android@10, they implemented a WebAssetLoader, which proxies requests through the https://localhost protocol. The WebAssetLoader acts like a private web server only accessible to your app. This was done because some web view features require you to be in a "secure context" (e.g. HTTPS) for the features to be enabled. In doing so, it does enable CORS enforcement.

Cordova android 9.x uses the plain old file system (file://), which didn't enforce CORs. This is why you see the XHR request work in 9. x but not in 10. x. You can make 10. x behave like 9. x by enabling the AndroidInsecureFileModeEnabled

So if you are using cordova-android@10 just add the following preference at config.xml:

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

I had the same problem and it solved it for me. :)

Upvotes: 2

Related Questions