Skip to content

Commit

Permalink
fix: use try/catch when setting xhr.responseType (#592)
Browse files Browse the repository at this point in the history
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
  • Loading branch information
darrachequesne committed Feb 18, 2018
1 parent 3039017 commit 64ce480
Showing 1 changed file with 13 additions and 6 deletions.
19 changes: 13 additions & 6 deletions lib/transports/polling-xhr.js
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,10 @@ Request.prototype.create = function () {
xhr.setRequestHeader('Accept', '*/*');
} catch (e) {}

if (this.supportsBinary) {
xhr.responseType = 'arraybuffer';
}

// ie6 check
if ('withCredentials' in xhr) {
xhr.withCredentials = true;
Expand All @@ -239,13 +243,12 @@ Request.prototype.create = function () {
} else {
xhr.onreadystatechange = function () {
if (xhr.readyState === 2) {
var contentType;
try {
contentType = xhr.getResponseHeader('Content-Type');
var contentType = xhr.getResponseHeader('Content-Type');
if (contentType !== 'application/octet-stream') {
xhr.responseType = 'text';
}
} catch (e) {}
if (contentType === 'application/octet-stream') {
xhr.responseType = 'arraybuffer';
}
}
if (4 !== xhr.readyState) return;
if (200 === xhr.status || 1223 === xhr.status) {
Expand Down Expand Up @@ -355,7 +358,11 @@ Request.prototype.onLoad = function () {
contentType = this.xhr.getResponseHeader('Content-Type');
} catch (e) {}
if (contentType === 'application/octet-stream') {
data = this.xhr.response || this.xhr.responseText;
if (this.xhr.responseType === 'arraybuffer') {
data = this.xhr.response || this.xhr.responseText;
} else {
data = String.fromCharCode.apply(null, new Uint8Array(this.xhr.response));
}
} else {
data = this.xhr.responseText;
}
Expand Down

0 comments on commit 64ce480

Please sign in to comment.