jQuery CORS fix for IE8 and IE9

No browser is left behind

Who can blame jQuery for not wanting to support Internet Explorer? Despite whatever the reason, it doesn’t always make business sense and we must support it. I found this piece of code that patches the issue with jQuery.

if ( window.XDomainRequest ) {
    jQuery.ajaxTransport(function( s ) {
        if ( s.crossDomain && s.async ) {
            if ( s.timeout ) {
                s.xdrTimeout = s.timeout;
                delete s.timeout;
            }
            var xdr;
            return {
                send: function( _, complete ) {
                    function callback( status, statusText, responses, responseHeaders ) {
                        xdr.onload = xdr.onerror = xdr.ontimeout = jQuery.noop;
                        xdr = undefined;
                        complete( status, statusText, responses, responseHeaders );
                    }
                    xdr = new XDomainRequest();
                    xdr.onload = function() {
                        callback( 200, "OK", { text: xdr.responseText }, "Content-Type: " + xdr.contentType );
                    };
                    xdr.onerror = function() {
                        callback( 404, "Not Found" );
                    };
                    xdr.onprogress = jQuery.noop;
                    xdr.ontimeout = function() {
                        callback( 0, "timeout" );
                    };
                    xdr.timeout = s.xdrTimeout || Number.MAX_VALUE;
                    xdr.open( s.type, s.url );
                    xdr.send( ( s.hasContent && s.data ) || null );
                },
                abort: function() {
                    if ( xdr ) {
                        xdr.onerror = jQuery.noop;
                        xdr.abort();
                    }
                }
            };
        }
    });
}

Note: This doesn’t work when using the {async: false} option in jQuery methods.

Be sure to set the {crossDomain: true} setting and you’re good to go.

Jun 20, 2014 Programming

Support this blog

Buy yourself ANYTHING!

That's right! Shop as you normally would using Amazon.com with my affiliate link and the commissions made go directly into keeping this blog healthy. It's that simple! The hardware and software costs used for this site comes out of my own pocket and it's expensive. Lets keep this site ad free :)

Start shopping on Amazon.com now!

Thank you!
Richard S.