Justin
Justin

Reputation: 45350

Detect if browser does not support XMLHttpRequest with full CORS support

How do I check if a browser supports the native JavaScript XMLHttpRequest object with CORS? I am testing in IE 8 which as I understood only supports XDomainRequest, however doing the following in IE 8:

typeof window.XMLHttpRequest
"object"

I would have thought that would be undefined. Basically how can I detect if a browser supports the full XMLHttpRequest with CORS support?

Should I do the inverse?

if(type window.XDomainRequest === 'object') {
    // Assume the browser does not support XMLHttpRequest with CORS
}

Upvotes: 0

Views: 726

Answers (1)

fred_
fred_

Reputation: 1696

I use this, 1 means XMLHttpRequest support cors, 2 means cors is supported via XDomainRequest, 0 means no CORS support

var  corsSupportLevel = null;    
function supportsCorsInternal() {

                if (corsSupportLevel !== null) return corsSupportLevel;

                var xhr = new XMLHttpRequest();
                if (typeof xhr.withCredentials !== 'undefined') {
                    // Supports CORS
                    corsSupportLevel = 1;
                } else if (typeof XDomainRequest !== "undefined") {
                    // IE
                    corsSupportLevel = 2;
                } else {
                    corsSupportLevel = 0;
                }
                return corsSupportLevel;
            }

Upvotes: 2

Related Questions