-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmozXhr.js
47 lines (41 loc) · 1.14 KB
/
mozXhr.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
export const MOZ_CHUNKED = 'moz-chunked';
export default function mozXhrRequest(options) {
const xhr = new XMLHttpRequest();
function onProgressEvent() {
const view = new Uint8Array(xhr.response);
let len = view.length;
const rawString = new Array(len);
while(len--) {
rawString[len] = String.fromCharCode(view[len]);
}
options.onRawChunk(rawString.join(''));
}
function onLoadEvent() {
options.onRawComplete({
statusCode: xhr.status,
transport: MOZ_CHUNKED,
raw: xhr
});
}
function onError(err) {
options.onRawComplete({
statusCode: 0,
transport: MOZ_CHUNKED,
raw: err
});
}
xhr.open(options.method, options.url);
xhr.responseType = 'moz-chunked-arraybuffer';
if (options.headers) {
Object.getOwnPropertyNames(options.headers).forEach(k => {
xhr.setRequestHeader(k, options.headers[k]);
})
}
if (options.credentials === 'include') {
xhr.withCredentials = true;
}
xhr.addEventListener('progress', onProgressEvent);
xhr.addEventListener('loadend', onLoadEvent);
xhr.addEventListener('error', onError);
xhr.send(options.body);
}