From 6c778bb39043eb17df2c223ffd81beb747d230e1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B6rn=20Ruberg?= Date: Thu, 2 Jul 2015 17:41:52 +0200 Subject: [PATCH] Support the XDomainRequest object of IE8 and IE9. Those browsers are not able to do CORS request via the common XHR object. By supporting the old api it is possible to fetch scripts from other domains with basket.js --- lib/basket.js | 73 +++++++++++++++++++++++++++++++++------------------ 1 file changed, 48 insertions(+), 25 deletions(-) diff --git a/lib/basket.js b/lib/basket.js index 5abff79..649e95d 100644 --- a/lib/basket.js +++ b/lib/basket.js @@ -46,32 +46,55 @@ var getUrl = function( url ) { var promise = new RSVP.Promise( function( resolve, reject ){ - - var xhr = new XMLHttpRequest(); - xhr.open( 'GET', url ); - - xhr.onreadystatechange = function() { - if ( xhr.readyState === 4 ) { - if ( ( xhr.status === 200 ) || - ( ( xhr.status === 0 ) && xhr.responseText ) ) { - resolve( { - content: xhr.responseText, - type: xhr.getResponseHeader('content-type') - } ); - } else { - reject( new Error( xhr.statusText ) ); + var xhr; + + if (typeof XDomainRequest === 'undefined') { + xhr = new XMLHttpRequest(); + + xhr.onreadystatechange = function() { + if ( xhr.readyState === 4 ) { + if ( ( xhr.status === 200 ) || + ( ( xhr.status === 0 ) && xhr.responseText ) ) { + resolve( { + content: xhr.responseText, + type: xhr.getResponseHeader('content-type') + } ); + } else { + reject( new Error( xhr.statusText ) ); + } } - } - }; - - // By default XHRs never timeout, and even Chrome doesn't implement the - // spec for xhr.timeout. So we do it ourselves. - setTimeout( function () { - if( xhr.readyState < 4 ) { - xhr.abort(); - } - }, basket.timeout ); + }; + // By default XHRs never timeout, and even Chrome doesn't implement the + // spec for xhr.timeout. So we do it ourselves. + setTimeout( function () { + if( xhr.readyState < 4 ) { + xhr.abort(); + } + }, basket.timeout ); + } + else { + /* XDomainRequest supports CORS ajax calls on IE8 and IE9 but with the following gotchas + * + * 1. The server protocol must be the same as the calling page protocol. + * 2. Only “text/plain” is supported for the request’s “Content Type header + * 3. No custom headers can be added to the request + */ + + xhr = new XDomainRequest(); + xhr.timeout = basket.timeout; + xhr.onload = function() { + resolve( { + content: xhr.responseText, + type: xhr.contentType + } ); + }; + xhr.onerror = function(error) { + reject( new Error( error ) ); + }; + } + + xhr.open( 'GET', url ); xhr.send(); }); @@ -85,7 +108,7 @@ if (!obj.skipCache) { addLocalStorage( obj.key , storeObj ); } - + return storeObj; }); };