forked from BLE-LTER/Zotero-JavaScript-Search-Client
-
Notifications
You must be signed in to change notification settings - Fork 1
/
cors.js
46 lines (40 loc) · 1.15 KB
/
cors.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
"use strict";
// adapted from https://www.html5rocks.com/en/tutorials/cors/
// Create the XHR object.
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
}
// Make the actual CORS request.
function makeCorsRequest(url, successCallback, errorCallback) {
var xhr = createCORSRequest("GET", url);
if (!xhr) {
alert("CORS not supported");
return;
}
// Response handlers.
xhr.onload = function () {
var headers = xhr.getAllResponseHeaders().split("\n");
var header_dict = {};
for (var i = 0; i < headers.length; i++) {
var parts = headers[i].split(": ");
header_dict[parts[0].toLowerCase()] = parts[1];
}
successCallback(header_dict, xhr.responseText);
};
xhr.onerror = function () {
errorCallback();
};
xhr.send();
}