Skip to content

Commit

Permalink
Fix reading ArrayBuffer into string on older browsers
Browse files Browse the repository at this point in the history
Android 4.0 doesn't like the `String.fromCharCode.apply` hack.
  • Loading branch information
mislav committed Nov 15, 2016
1 parent d7b6b8a commit 6f8529e
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 4 deletions.
14 changes: 11 additions & 3 deletions fetch.js
Expand Up @@ -178,6 +178,16 @@
return promise
}

function readArrayBufferAsText(buf) {
var view = new Uint8Array(buf)
var chars = new Array(view.length)

for (var i = 0; i < view.length; i++) {
chars[i] = String.fromCharCode(view[i])
}
return chars.join('')
}

function bufferClone(buf) {
if (buf.slice) {
return buf.slice(0)
Expand Down Expand Up @@ -252,9 +262,7 @@
if (this._bodyBlob) {
return readBlobAsText(this._bodyBlob)
} else if (this._bodyArrayBuffer) {
var view = new Uint8Array(this._bodyArrayBuffer)
var str = String.fromCharCode.apply(null, view)
return Promise.resolve(str)
return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer))
} else if (this._bodyFormData) {
throw new Error('could not read FormData body as text')
} else {
Expand Down
8 changes: 7 additions & 1 deletion test/test.js
Expand Up @@ -64,7 +64,13 @@ function arrayBufferFromText(text) {
}

function readArrayBufferAsText(buf) {
return String.fromCharCode.apply(null, new Uint8Array(buf))
var view = new Uint8Array(buf)
var chars = new Array(view.length)

for (var i = 0; i < view.length; i++) {
chars[i] = String.fromCharCode(view[i])
}
return chars.join('')
}

var preservedGlobals = {}
Expand Down

0 comments on commit 6f8529e

Please sign in to comment.