如何检测浏览器是否接受addEventListener的xmlhttprequest事件?

时间:2016-06-20 14:18:26

标签: javascript events xmlhttprequest addeventlistener

对象内的此函数定义xmlhttprequest对象的事件处理。由于某些浏览器不接受addEventListener方法,我做了一个测试,如果没有,它将定义onstatechange:

var reqEngatilhar = function(){
    este.concluido = false;
    timeoutId = setTimeout(reqTimeout, este.timeout);
    if(este.Request.hasOwnProperty("onload")){
        este.Request.addEventListener("error", reqErro, true);
        este.Request.addEventListener("progress", reqMon, false);
        este.Request.addEventListener("abort", reqAbort, false);
        este.Request.addEventListener("load", reqFim, false);
        console.log("$Http reqEngatilhar usando eventos...");
    } else {
        este.Request.onreadystatechange = function (e) { reqSwitch(e); };
        console.log("$Http reqEngatilhar usando onreadystatechange...");
    }
}

" este"是"这个"在函数外部(var este = this;)

" reqSwitch"将指向正确的功能。问题是测试este.Request.hasOwnProperty(" onload")仅适用于Safari。如何进行跨浏览器测试以检测浏览器是否可以使用addEventListener?

4 个答案:

答案 0 :(得分:3)

只需检查对象是否将addEventListener设置为真值。通过这种方式执行检查,您不依赖于浏览器在幕后使用的原型层次结构。 (如dandavis pointed out,这可能是个问题。)

if (este.Request.addEventListener) {
    este.Request.addEventListener("error", reqErro, true);
    // etc...
} else {
    este.Request.onreadystatechange = function (e) { reqSwitch(e); };
    console.log("$Http reqEngatilhar usando onreadystatechange...");
}

如果您担心可以解决问题并将addEventListener设置为时髦值的工具,您可以这样做:

if (typeof este.Request.addEventListener === "function") {

答案 1 :(得分:0)

尝试:

var util = {
    getAttribute: function (dom, attr) {
        if (dom.getAttribute !== undefined) {
            return dom.getAttribute(attr);
        } else if (dom[attr] !== undefined) {
            return dom[attr];
        } else {
            return null;
        }
    },
    addEvent: function (obj, evtName, func) {
        //Primero revisar attributos si existe o no.
        if (obj.addEventListener) {
            obj.addEventListener(evtName, func, false);

        } else if (obj.attachEvent) {
            obj.attachEvent(evtName, func);
        } else {
            if (this.getAttribute("on" + evtName) !== undefined) {
                obj["on" + evtName] = func;
            } else {
                obj[evtName] = func;
            }

        }

    },
    removeEvent: function (obj, evtName, func) {
        if (obj.removeEventListener) {
            obj.removeEventListener(evtName, func, false);
        } else if (obj.detachEvent) {
            obj.detachEvent(evtName, func);
        } else {
            if (this.getAttribute("on" + evtName) !== undefined) {
                obj["on" + evtName] = null;
            } else {
                obj[evtName] = null;
            }
        }

    },
    getAjaxObject: function () {
        var xhttp = null;
        //XDomainRequest
        if ("XMLHttpRequest" in window) {
            xhttp = new XMLHttpRequest();
        } else {
            // code for IE6, IE5
            xhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        return xhttp;
    }

};

//START CODE HERE.

var xhr = util.getAjaxObject();

var isUpload = (xhr && ('upload' in xhr) && ('onprogress' in xhr.upload));

if (isUpload) {
    util.addEvent(xhr, "progress", xhrEvt.onProgress());
    util.addEvent(xhr, "loadstart", xhrEvt.onLoadStart);
    util.addEvent(xhr, "abort", xhrEvt.onAbort);
}

util.addEvent(xhr, "readystatechange", xhrEvt.ajaxOnReadyState);

var xhrEvt = {
    onProgress: function (e) {
        if (e.lengthComputable) {
            //Loaded bytes.
            var cLoaded = e.loaded;
        }
    },
    onLoadStart: function () {
    },
    onAbort: function () {
    },
    onReadyState: function () {
        var state = xhr.readyState;
        var httpStatus = xhr.status;

        if (state === 4 && httpStatus === 200) {
            //Completed success.
        }

    }
};

//CONTINUE YOUR CODE HERE.

答案 2 :(得分:-1)

addEventListener polyfill可能对您有所帮助:

https://github.com/jonathantneal/EventListener

省去检查浏览器兼容性的麻烦,让polyfill处理它。

答案 3 :(得分:-1)

尝试使用较旧的方式注册活动吗?

    // Pass a function reference — do not add '()' after it, which would call the function!
el.onclick = modifyText;

// Using a function expression
element.onclick = function() {
  // ... function logic ...
};

查看this post了解详情。