Pergunta

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.

Foi útil?

Solução

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

Outras dicas

Are you sure it's actually supposed to throw an exception? I can't see anything in the specifications: http://www.w3.org/TR/XMLHttpRequest/#exceptions Looks like it does. My bad.

In either case, you can always check the domain of the incoming string against the domain of the page the user is currently on.


FWIW, as you can see by this jsFiddle (open up Web Inspector), Chrome doesn't really throw an exception. It just says "Failed to load resource".

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top