Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if browser will accept xmlhttprequest events by addEventListener?

This function inside an object define the event handling for a xmlhttprequest object. As some browsers did not accept the addEventListener method, I did a test so if not, it will define 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...");
    }
}

The "este" is "this" outside the function (var este = this;)

The "reqSwitch" will point to the right funcion. The problem is the test este.Request.hasOwnProperty("onload") works only in Safari. How can I make a cross-browser test to detect if the browser will work with addEventListener?

like image 971
Gustavo Avatar asked Jun 20 '16 14:06

Gustavo


1 Answers

Just check whether the object has addEventListener set to a truthy value. By performing the check this way, you are not dependent on the prototype hierarchy that the browser uses behind the scenes. (As dandavis pointed out, it can be a problem.)

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...");
}

If you are concerned about tools that could muck things and set addEventListener to funky values, you could do:

if (typeof este.Request.addEventListener === "function") {
like image 86
Louis Avatar answered Oct 06 '22 00:10

Louis