Search code examples
javascriptxmlhttprequestsame-origin-policy

Catching same origin exception in Javascript?


I'm trying to create my own XMLHttpRequest framework to learn how this things work internally. A thing that puzzles me is that I cannot find how to catch a "Same origin" exception.

The idea behind this is that I try to load a URL, if I get a Same origin exception, I re-request the URL through a proxy script local for the script. The reason I do this is because I need to access production data from a development sandbox and I want it to be as transparent as possible for the script itself.

I know it's a bad practice but this is the least intrusive way of doing this at the moment :)

Just to clear things - I don't want to bypass same origin, I just want to catch the thrown exception so I can do something about it.

Here is the code I currently use for my xhr:

var net = function (url, cb, setts){
    this.url = url;
    this.cb = cb;

    var oThis = this;
    if (!this.xhr) {
        this.xhr = new XMLHttpRequest();
        this.xhr.onreadystatechange = function() {
            if (oThis.xhr.readyState == 4 && oThis.xhr.status == 200) {
                document.body.innerHTML += "RS: "+oThis.xhr.readyState+"; ST:"+oThis.xhr.status+"; RP:"+oThis.xhr.responseText+"<br>";
            }
            else {
                // do some other stuff :)
                document.body.innerHTML += "RS: "+oThis.xhr.readyState+"; ST:"+oThis.xhr.status+"; RP:"+oThis.xhr.responseText+"<br>";
            }
        }
    }
    this.xhr.open("GET", url,true);
    this.xhr.send();
} // It's WIP so don't be scared about the unused vars or hardcoded values :)

I've tried to try...catch around xhr.send(); but no avail, still can't catch the exceptions.

Any ideas or pointers would be greatly appreciated.


Solution

  • xhr.onreadystatechange = function() {
        if (xhr.readyState==4) {
            if (xhr.status==0) {
                alert("denied");
            } else {
                alert("allowed");
            }
        }
    }