Skip to content

Commit 64ce480

Browse files
fix: use try/catch when setting xhr.responseType (#592)
Some XHR implementations (like Firefox WebWorker, react-native and some Android 4.x versions) throw an exception when setting xhr.responseType = 'arraybuffer' when xhr.readyState === 2 (which is perfectly valid, spec-wise). That commit fixes that behaviour by reverting some of the changes from #562 for those implementations. Fixes #589 Closes #590
1 parent 3039017 commit 64ce480

File tree

1 file changed

+13
-6
lines changed

1 file changed

+13
-6
lines changed

lib/transports/polling-xhr.js

+13-6
Original file line numberDiff line numberDiff line change
@@ -220,6 +220,10 @@ Request.prototype.create = function () {
220220
xhr.setRequestHeader('Accept', '*/*');
221221
} catch (e) {}
222222

223+
if (this.supportsBinary) {
224+
xhr.responseType = 'arraybuffer';
225+
}
226+
223227
// ie6 check
224228
if ('withCredentials' in xhr) {
225229
xhr.withCredentials = true;
@@ -239,13 +243,12 @@ Request.prototype.create = function () {
239243
} else {
240244
xhr.onreadystatechange = function () {
241245
if (xhr.readyState === 2) {
242-
var contentType;
243246
try {
244-
contentType = xhr.getResponseHeader('Content-Type');
247+
var contentType = xhr.getResponseHeader('Content-Type');
248+
if (contentType !== 'application/octet-stream') {
249+
xhr.responseType = 'text';
250+
}
245251
} catch (e) {}
246-
if (contentType === 'application/octet-stream') {
247-
xhr.responseType = 'arraybuffer';
248-
}
249252
}
250253
if (4 !== xhr.readyState) return;
251254
if (200 === xhr.status || 1223 === xhr.status) {
@@ -355,7 +358,11 @@ Request.prototype.onLoad = function () {
355358
contentType = this.xhr.getResponseHeader('Content-Type');
356359
} catch (e) {}
357360
if (contentType === 'application/octet-stream') {
358-
data = this.xhr.response || this.xhr.responseText;
361+
if (this.xhr.responseType === 'arraybuffer') {
362+
data = this.xhr.response || this.xhr.responseText;
363+
} else {
364+
data = String.fromCharCode.apply(null, new Uint8Array(this.xhr.response));
365+
}
359366
} else {
360367
data = this.xhr.responseText;
361368
}

0 commit comments

Comments
 (0)