如何特征检测XMLHttpRequest是否支持responseType=“”;阵列缓冲器”;

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

本文关键字:阵列 缓冲器 responseType 特征检测 XMLHttpRequest 是否 支持      更新时间:2023-09-26

我想知道浏览器是否支持XMLHttpRequest.responseType = "arraybuffer"。问题是,我不能再次测试一些"通用"xhr2支持,因为iOS 4.2有部分xhr2的支持,其中包括(即)XMLHttpRequestUpload,但不包括responseType = "arraybuffer"

我正在使用以下内容:

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

在我测试的所有支持此功能的浏览器中,responseType的默认值都是一个空字符串(就像规范中所说的那样:http://www.w3.org/TR/XMLHttpRequest/#the-responsetype属性),在不支持responsetype的浏览器中,该属性的值是未定义的。

检查ArrayBuffer应该是一个很好的特征检测。

如果userAgent支持ArrayBuffer对象,那么它很可能会与XHR2 一起工作

然而,如前所述,最好进行特征测试,而不是特征检测。

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();
}

responseType设置为"arraybuffer",并检查是否得到新值:

// 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;
}

你试过这样的东西吗?

if(typeof(XMLHttpRequestUpload) == "undefined"){
    //not supported
}

编辑

我想你可能会被一些像这样恶心的东西卡住

function IsArrayBufferSupported(){
    var xhr = new XMLHttpRequest();
    xhr.open('GET', '/', true);
    try{
       xhr.responseType = "arraybuffer";
       return true;
    }catch(e){return false;}
}

使用Modernizr这在Modernizr.xhr2中有介绍。跟进关于部分支持Modernizr.dataview的评论可能会更准确。

(function(modernizr, ns){
    ns.isSupported = (function(){
        return modernizr.xhr2 && modernizr.dataview;
    });
    return ns;
}(window.Modernizr, window.NameSpace || {}));

我希望这两个功能都能得到支持或不支持。

如果您只想检测是否支持"arraybuffer"响应,只需检查它是否在全局对象中即可。如果您想检测其他功能,只需指定XHR().responseType,直到浏览器清空它""或抛出错误。

function isAjaxResponseSupported(type) {
    var xhr = new XMLHttpRequest;
    /* Check if .responseType is supported first */
    if (typeof xhr.responseType === 'string') {
        /* Some browsers throw error for invalid .responseType */
        try {
            xhr.responseType = type;
            // If they don't,
            // check if .responseType is equal to @type.
            return xhr.responseType === type;
        } catch (e) {
            return false;
        }
    ; else return false;        
}