From 721d5864fb9cfcdfc8059fe00d71c0f720cc1f4f Mon Sep 17 00:00:00 2001 From: Damien Arrachequesne Date: Sun, 18 Feb 2018 10:37:17 +0100 Subject: [PATCH] fix: use try/catch when setting xhr.responseType 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 https://github.com/socketio/engine.io-client/pull/562 for those implementations. Closes #590 --- lib/transports/polling-xhr.js | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/lib/transports/polling-xhr.js b/lib/transports/polling-xhr.js index 297bac59e..52048fe65 100755 --- a/lib/transports/polling-xhr.js +++ b/lib/transports/polling-xhr.js @@ -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; @@ -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) { @@ -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; }