Skip to content

Commit

Permalink
Merge pull request #58 from Shopify/ie9-cors-support
Browse files Browse the repository at this point in the history
[FIX] Support the network layer in IE9
  • Loading branch information
minasmart committed Mar 30, 2016
2 parents 8bd4a8c + 22348e0 commit 3d46d53
Show file tree
Hide file tree
Showing 3 changed files with 73 additions and 1 deletion.
2 changes: 1 addition & 1 deletion examples/cart/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<title>JS Buy SDK Example -- Cart 001</title>
<link rel="stylesheet" href="index.css">
<script src="//code.jquery.com/jquery-2.2.1.min.js"></script>
<script src="/shopify-buy.globals.js"></script>
<script src="/shopify-buy.polyfilled.globals.js"></script>
<script src="/examples/cart/index.js"></script>
</head>
<body>
Expand Down
7 changes: 7 additions & 0 deletions src/ajax.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import ie9Ajax from './ie9-ajax';

function checkStatus(response) {
if (response.status >= 200 && response.status < 300) {
return response;
Expand Down Expand Up @@ -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)
Expand Down
65 changes: 65 additions & 0 deletions src/ie9-ajax.js
Original file line number Diff line number Diff line change
@@ -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;

0 comments on commit 3d46d53

Please sign in to comment.