forked from dailymotion/vast-client-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathxhr_url_handler.js
48 lines (43 loc) · 1.11 KB
/
xhr_url_handler.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
47
48
function xhr() {
try {
const request = new window.XMLHttpRequest();
if ('withCredentials' in request) {
// check CORS support
return request;
}
return null;
} catch (err) {
return null;
}
}
function supported() {
return !!xhr();
}
function get(url, options, cb) {
if (window.location.protocol === 'https:' && url.indexOf('http://') === 0) {
return cb(new Error('XHRURLHandler: Cannot go from HTTPS to HTTP.'));
}
try {
const request = xhr();
request.open('GET', url);
request.timeout = options.timeout || 0;
request.withCredentials = options.withCredentials || false;
request.overrideMimeType && request.overrideMimeType('text/xml');
request.onreadystatechange = function() {
if (request.readyState === 4) {
if (request.status === 200) {
cb(null, request.responseXML);
} else {
cb(new Error(`XHRURLHandler: ${request.statusText}`));
}
}
};
request.send();
} catch (error) {
cb(new Error('XHRURLHandler: Unexpected error'));
}
}
export const XHRURLHandler = {
get,
supported
};