Detecting CORS support in a browser

I’m using the following JavaScript function to detect whether a browser has support for Cross-Origin Resource Sharing (CORS) XHR.

function browserSupportsCors() {

	if ("withCredentials" in new XMLHttpRequest())
		return true;	
	else if (window.XDomainRequest)
		return true;
	else
		return false;
}

The XDomainRequest object is specific to IE 8 and IE9, other browsers, including IE 10, extend the existing XMLHttpRequest.

I use this piece of code in the Json2Ldap directory Ajax demo which I posted the other day.

jQuery still has no complete and robust plugin for CORS support. I hope this situation will change soon as browser support for CORS has passed 80%.

PS July 2012: Update of the CORS detection code to handle IE 9 better.

  • Works like charm. Thanks.