Detect browser support for cross-domain XMLHttpRequests?

Posted on

Detect browser support for cross-domain XMLHttpRequests? – Even if we have a good project plan and a logical concept, we will spend the majority of our time correcting errors abaout javascript and xmlhttprequest. Furthermore, our application can run without obvious errors with JavaScript, we must use various ways to ensure that everything is operating properly. In general, there are two types of errors that you’ll encounter while doing something wrong in code: Syntax Errors and Logic Errors. To make bug fixing easier, every JavaScript error is captured with a full stack trace and the specific line of source code marked. To assist you in resolving the JavaScript error, look at the discuss below to fix problem about Detect browser support for cross-domain XMLHttpRequests?.

Problem :

I’m working on some Javascript that makes use of Firefox 3.5’s ability to perform cross-domain XMLHttpRequests… But I’d like to fail gracefully if they aren’t supported.

Apart from actually making a cross-domain request, is there any way to detect a browser’s support for them?

Solution :

For future reference, full CORS feature detection should look something like this:

//Detect browser support for CORS
if ('withCredentials' in new XMLHttpRequest()) {
    /* supports cross-domain requests */
    document.write("CORS supported (XHR)");
else if(typeof XDomainRequest !== "undefined"){
  //Use IE-specific "CORS" code with XDR
  document.write("CORS supported (XDR)");
  //Time to retreat with a fallback or polyfill
  document.write("No CORS Support!");

You can try this test live using JSBin and see the proper response in IE, Firefox, Chrome, Safari, and Opera.

There are some edge cases in non-browser environments that do support cross-domain XHR but not XHR2/CORS. This test does not account for those situations.

According to you should be able to use:

if ('withCredentials' in new XMLHttpRequest()) {
    /* supports cross-domain requests */

(Note: there is a comment on that page that Chrome 2 fails this test [although it does support cross-domain requests]. I tested Chrome 3 and the test is now passing.)

Keep in mind that just because the browser might support the cross-domain API does not mean the target server will allow the request to complete.

You might want to look at EasyXDM, which wraps cross-browser quirks and provides an easy-to-use API for communicating in client script between different domains using the best available mechanism for that browser (e.g. postMessage if available, other mechanisms if not).

Clearly that library has solved the browser-capabilities detection problem, so you can benefit from their experience. 🙂

IE8 also has XDomainRequest object that can be used to retrieve RSS as text which can later be parsed into DOM.

Leave a Reply

Your email address will not be published. Required fields are marked *