Question

I am interested in seeing what minimal cross-browser Javascript code (jQuery is fine too) might be possible for verifying whether a site I wish to send cross-domain AJAX requests has support for CORS.

I know jQuery has a method to check whether the browser supports it. But I'd really like to be able to check if the remote site also supports it.

I thought I just had to check for a HTTP header but of course the XHR will throw an exception when trying to do a cross-domain request to a site which doesn't specifically support it.

But is there a way to check that an exception thrown by XMLHttpRequest was due to the site not supporting CORS rather than something else going wrong? (It doesn't have to support XDomainRequest.)

In any case I'm not sure the best minimal/fastest cross-browser way to to fetch an HTTP HEAD using AJAX, which I assume is the lightweight way rather than fetching a page, etc.

Use case: Once I know whether the browser and AJAX provider support CORS or not, I can choose whether to send the more featureful JSON/CORS requests or fall back to JSONP requests when necessary.

Was it helpful?

Solution

As far as the specification, it's not possible.

If there is a network error: In case of DNS errors, TLS negotiation failure, or other type of network errors, apply the network error steps. Do not request any kind of end user interaction...

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

There is no special way to identify the case in which CORS is not allowed, since the network error steps are applied in any case.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top