Search code examples
javascriptinternet-explorer-8xmlhttprequestxdomainrequest

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
}

Solution

  • 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;
                }