Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is XHR allowed within web-worker in PhoneGap/Cordova?

Environment: Cordova 2.9.0, iOS (Xcode 4.6.3 iPad 6.1 Simulator and iPad 3 running iOS 6.1.3)

I am trying to separate out the processing of loading another file into a web-worker. The file I am loading is part of the application (meaning it is in the same domain).

The following code works fine when NOT run in a web-worker: (url is of the form "/db/file.json")

function loadXMLDoc(url, successCallback) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState==4 && (xmlhttp.status==200 || xmlhttp.status == 0)) {
        successCallback(xmlhttp.responseText);
    }
}
xmlhttp.open("GET",url,true);
xmlhttp.send();
}

NOTE: status is always 0 when using cordova. status is 200 when not using cordova.

When I separate this code into a web-worker the responseText comes back empty.

I removed phoneGap and verified that the code above worked with and without a web-worker.

Is it possible to use XHR in a web-worker within phoneGap/cordova?

like image 940
user2554909 Avatar asked Dec 03 '25 05:12

user2554909


1 Answers

You will likely want to check that your server properly supports Cross Origin Resource Sharing. There are some handy resources for this, such as CORS Enabled, by the W3C.

When you run this without Cordova, you're likely actually loading a page from a server, such as http://www.myserver.com/index.html, but when you run it from Cordova, you're actually running file:///somedirectory/www/index.html. This means that if you attempt to use an ajax request to access information from myserver.com, it is on a different domain, and if not properly set up, the browser will reject the response.

The most important thing you can do is enable Cross-Origin Resource Sharing. This requires adding a new header Access-Control-Allow-Origin who's value is *

like image 53
Jamie Starke Avatar answered Dec 06 '25 12:12

Jamie Starke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!