views:

50

answers:

1

http://www.w3.org/TR/access-control/

Reading the CORS spec linked above, it seems to be the case that it's impossible to reliably distinguish between a generic "network error" and a cross-origin access denied error. From the spec:

If there is a network error Apply the network error steps.

Perform a resource sharing check. If it returns fail, apply the network error steps.

http://www.w3.org/TR/access-control/#simple-cross-origin-request0

In my testing, I couldn't locate any features of Firefox's implementation that seem to indicate that the resource sharing check definitely failed. It just switches readyState to 4 and sets status to 0.

Ultimately I'd like the ability to pass a success callback, a general fail callback, and an optional cross-origin fail callback, to my function. Thanks for any help or insight.

A: 

You likely do not need to make the XHR request to know when a cross-origin error is going to occur. Try the following based on jQuery's $.get:

var xhr = {
    get: function(url, data, callback, dataType) {
        if ( !this.isSameOrigin(url) ) {
            callback(null, "Same-origin error or whatever", null);
        }

        $.get(url, data, callback, dataType);
    },

    isSameOrigin: function(url) {
        // Do a string comparison against window.location.  Get as complicated 
        // as you'd like
        return !!(
            // Url doesn't contain a valid protocol (relative to domain))
            !url.match(/^https?:\/\//i) || 
            // Url contains a protocol but the request is to the current domain
            url.match(new RegExp("^https?://" + window.location.host, "i"))
        );
    }
};
Justin Johnson
I'm talking about cross-origin resource sharing, not traditional ajax. In which case you have to make the request, since the response headers are needed before the client can determine whether there is a cross-origin failure.
greim
You tagged this as xhr and xmlhttprequest, both of which are AJAX. How are you retrieving the resources otherwise? At any rate, since it's a standard browser security measure you *don't* have to make an AJAX request will fail because of the same-origin policy. The only exception is when you don't know if you're doing a JSONP request or not, which you should.
Justin Johnson
The latest versions of XHR allow exceptions to the same-origin policy. But for there to be an exception, there need to be certain response headers. See link at the top of my OP.
greim