Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

how to bypass Access-Control-Allow-Origin with javascript only? WordPress


My plugin allows loading displaying gpx-track files - see a demo here: [[LINK href=""]][[/LINK]]
The problem is when I try to load a .gpx file from another subdomain with the following code, which at least on my test site fails:

_load_xml: function(url, cb, options, async) {
if (async == undefined) async = this.options.async;
if (options == undefined) options = this.options;

var xhr = new XMLHttpRequest();
if ('withCredentials' in xhr) {'GET', url, async);
} else if (typeof XDomainRequest != "undefined") {
xhr = new XDomainRequest(); //for IE'GET', url);
} else {'GET', url, async);
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
xhr.setRequestHeader('Access-Control-Allow-Methods', 'GET');

try {
xhr.overrideMimeType('text/xml'); // unsupported by IE
} catch(e) {}

xhr.onreadystatechange = function() {
if (xhr.readyState != 4) return;
if(xhr.status == 200){
cb(xhr.responseXML, options);
}else {
var parser = new DOMParser();
cb(parser.parseFromString(xhr.response, "text/xml"), options);
} catch (e){
} else {
alert(url+' could not be loaded - please check if the file exists and if it is loaded from the same domain as the website!');

As far as I understand, the server from which the file should be loaded, has to support CORS, right? Or does the server which loads the file has to support CORS?
Is there a workaround to make this work on my server too?
FYI - jquery is not an option, all solutions would have to be implmented in the javascript-code above, libraries like easyXDM are also not an option.

Answers (1)


Ross Wilson answers:

The most reliable way is to actually proxy your requests through a php script. When PHP uses CURL it does not require any additional cross-scripting or access control modifications.

Include something like this on the same domain you are doing the request from, and then update your code above to use point to the location of this proxy script, passing the url you want it to retrieve.
[[LINK href=""]][[/LINK]]

Robert Seyfriedsberger comments:

thx - will try that

Robert Seyfriedsberger comments:

That will work - thx.