diff --git a/examples/cart/index.html b/examples/cart/index.html index 8e8995162..2b651df9b 100644 --- a/examples/cart/index.html +++ b/examples/cart/index.html @@ -5,7 +5,7 @@ JS Buy SDK Example -- Cart 001 - + diff --git a/src/ajax.js b/src/ajax.js index dfd496516..195fd082f 100644 --- a/src/ajax.js +++ b/src/ajax.js @@ -1,3 +1,5 @@ +import ie9Ajax from './ie9-ajax'; + function checkStatus(response) { if (response.status >= 200 && response.status < 300) { return response; @@ -25,7 +27,12 @@ function parseResponse(response) { } export default function ajax(method, url, opts = {}) { + if (window.XDomainRequest) { + return ie9Ajax(...arguments); + } + opts.method = method; + opts.mode = 'cors'; return fetch(url, opts) .then(checkStatus) diff --git a/src/ie9-ajax.js b/src/ie9-ajax.js new file mode 100644 index 000000000..d6badfe65 --- /dev/null +++ b/src/ie9-ajax.js @@ -0,0 +1,65 @@ +function authToUrl(url, opts) { + let authorization; + + if (opts.headers) { + Object.keys(opts.headers).forEach(key => { + if (key.toLowerCase() === 'authorization') { + authorization = opts.headers[key]; + } + }); + } + + if (authorization) { + const hashedKey = authorization.split(' ').slice(-1)[0]; + + try { + const plainKey = atob(hashedKey); + + let newUrl; + + if (url.indexOf('?') > -1) { + newUrl = `${url}&_x_http_authorization=${plainKey}`; + } else { + newUrl = `${url}?_x_http_authorization=${plainKey}`; + } + + return newUrl; + } catch (e) { + // atob choked on non-encoded data. Therefore, not a form of auth we + // support. + // + // NOOP + // + } + } + + return url; +} + +function ie9Ajax(method, url, opts) { + return new Promise(function (resolve, reject) { + const xdr = new XDomainRequest(); + + xdr.onload = function () { + try { + const json = JSON.parse(xdr.responseText); + + resolve({ json, originalResponse: xdr, isJSON: true }); + } catch (e) { + resolve({ text: xdr.responseText, originalResponse: xdr, isText: true }); + } + }; + + function handleError() { + reject(new Error('There was an error with the XDR')); + } + + xdr.onerror = handleError; + xdr.ontimeout = handleError; + + xdr.open(method, authToUrl(url, opts)); + xdr.send(opts.data); + }); +} + +export default ie9Ajax;