Catching same origin exception in Javascript?

浪子不回头ぞ 提交于 2019-12-07 16:48:35

问题


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.


回答1:


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



回答2:


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".



来源:https://stackoverflow.com/questions/4318658/catching-same-origin-exception-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!