Search code examples
androidcordovawhitelist

Cannot send cross domain requests with Cordova. Whitelisting doesn't work


I cannot make cross domain request using Cordova. Spent several hours on this and still not sure what is wrong. Maybe someone has dealt with problem like this? Thanks!

.js file:

//works fine, test.html - local file
  $.get("test.html",function(data,status){
    alert("Data: " + data + "\nStatus: " + status);
  });

//does not do anything
  $.get("http://www.stackoverflow.com",function(data,status){
    alert("Data: " + data + "\nStatus: " + status);
  });

Project Config file:

..
<access origin="stackoverflow.com"/>
..

Also Tried:

 <access origin="www.stackoverflow.com"/>
 <access origin="http://www.stackoverflow.com"/>
 <access origin="*"/>

AndroidManifest.xml:

..
<uses-permission android:name="android.permission.INTERNET" />
..

Solution

  • I was having the same problem... after some researches I found a way to do this. Use the jQuery $.ajax to make a "GET" request.
    (In reality, I was trying to access a SOAP WebService, then I found this way to use a POST or GET request)
    Test here in the JSFiddle.
    You still need the access origin though...

    Obs: Your request will not work, unless the page you are trying to get, allow you to do this. The example page allow the access, so... try accessing it from your Cordova app.

    $.ajax({
                type: 'GET',
                url: "http://anytime.ueuo.com/http-return.php",
                crossDomain: true,
                success: function (data, textStatus, jqXHR) {
                    alert("Ok!");
                    $("#retorno").html(data);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    alert("Wait, take a look: " + textStatus + ", " + errorThrown);
                },
                complete: function (jqXHR, textStatus ) {
                    alert("Status: " + textStatus);
                }
            });
    

    Obs-2: Your code return the error: XMLHttpRequest cannot load http://www.stackoverflow.com/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8383' is therefore not allowed access. (02:18:52:813 | error, javascript) at public_html/index.html. That's why you need to test with a pre-configured page.

    Sorry for my bad-english '-'