How to detect if the browser accepts xmlhttprequest events?

Asked

Viewed 38 times

1

It is the following, gurizada, to make my object compatible with old browsers (if not swear me) I created a new problem. It is difficult to deviate the path according to the browser version because it was not so standardized, the browsers accepted one resource and another not, so I did the following:

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

This little function defines the events within my object when it changes the state of the xmlhttprequest request (where this=this outside of the function). But some browsers do not accept events via addeventlistener, so it sets onreadystatechange that will make the "distribution" by calling the right function.

The problem is the test this.Request.hasOwnProperty("onload") which is working only for Safari (my site only opens in Safari kkkkk).

So I ask: what is the correct (or best possible) way to detect if the browser accepts xmlhttprequest events via addeventlistener?

  • Why don’t you use on... for everyone? What browsers do you want to support? IE7?

  • I have been using MDN as a reference, and it seems to use addeventlistener is the trend. IE7 does not interest me, but even IE9 gives a few problems. I did this function because it gave problem where should not, but I did not write the browser/ version - my fault.

1 answer

0

Do so:

if(window.XMLHttpRequest && !(window.ActiveXObject)) {
    try {
        req = new XMLHttpRequest();
    } catch(e) {
        req = false;
    }
} else if(window.ActiveXObject) { // Se for IE usa o control ActiveX
    try {
        req = new ActiveXObject("Msxml2.XMLHTTP");
    } catch(e) {
        try {
            req = new ActiveXObject("Microsoft.XMLHTTP");
        } catch(e) {
            req = false;
        }
    }
}
return req;

Full reference: https://github.com/pmcfernandes/r/blob/master/Linq.js

  • That answer has nothing to do with the question.

  • I am exemplifying how the code works for all browsers. I think if the person is at least intelligent they will take advantage of it. The stack is not a site of fixes but help to fix and write code there are other sites like freelancer

Browser other questions tagged

You are not signed in. Login or sign up in order to post.