Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to feature detect if XMLHttpRequest supports responseType = "arraybuffer"?

I want to know if the browser supportes XMLHttpRequest.responseType = "arraybuffer". Problem is, that I can not test agains some "general" xhr2 support, since iOS 4.2 has partial xhr2 support which includes (i.e.) XMLHttpRequestUpload but not responseType = "arraybuffer".

like image 295
Aron Woost Avatar asked Jan 19 '12 13:01

Aron Woost


3 Answers

I am using the following:

var supported = typeof new XMLHttpRequest().responseType === 'string';

In all browsers I tested that support this, the default value of responseType is an empty string (just like it says in the spec: http://www.w3.org/TR/XMLHttpRequest/#the-responsetype-attribute ), in browsers that don't support responseType the value of the attribute is undefined.

like image 155
bwindels Avatar answered Oct 03 '22 19:10

bwindels


Checking of ArrayBuffer should be a good feature detection.

If a userAgent supports the ArrayBuffer object then it's likely it will work with XHR2

However as noted, it would be best to do a feature test and not a feature detection.

function IsArrayBufferSupported(cb){
    var xhr = new XMLHttpRequest();
    xhr.open('GET', '/', true);
    try {
       xhr.responseType = "arraybuffer";
    } catch (e){
        return cb(false);
    }
    xhr.onload = function onload() {
        if (ArrayBuffer.prototype.isPrototypeOf(this.response)) {
            return cb(true);
        }
        cb(false);
    }
    xhr.send();
}
like image 20
Raynos Avatar answered Oct 03 '22 18:10

Raynos


Set responseType to "arraybuffer" and check if it got the new value:

// call like isResponseTypeSupported('arraybuffer')
function isResponseTypeSupported(responseType) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', '/');
    try {
        xhr.responseType = responseType;
    } catch (e) {
        return false;
    }
    return xhr.responseType === responseType;
}
like image 44
flacs Avatar answered Oct 03 '22 17:10

flacs