Agregue un "gancho" a todas las solicitudes AJAX en una página

Resuelto Yuliy asked hace 13 años • 9 respuestas

Me gustaría saber si es posible "enganchar" cada solicitud AJAX (ya sea cuando está a punto de enviarse o en eventos) y realizar una acción. En este punto, supongo que hay otros scripts de terceros en la página. Algunos de ellos pueden usar jQuery, mientras que otros no. es posible?

Yuliy avatar Mar 05 '11 14:03 Yuliy
Aceptado

NOTA: La respuesta aceptada no produce la respuesta real porque se llama demasiado pronto.

Puede hacer esto, que interceptará genéricamente cualquier AJAX globalmente y no arruinará ninguna devolución de llamada, etc. que tal vez haya sido asignada por bibliotecas AJAX de terceros.

(function() {
    var origOpen = XMLHttpRequest.prototype.open;
    XMLHttpRequest.prototype.open = function() {
        console.log('request started!');
        this.addEventListener('load', function() {
            console.log('request completed!');
            console.log(this.readyState); //will always be 4 (ajax is completed successfully)
            console.log(this.responseText); //whatever the response was
        });
        origOpen.apply(this, arguments);
    };
})();

Algunos documentos más sobre lo que puede hacer aquí con la API addEventListener aquí:

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Monitoring_progress

(Tenga en cuenta que esto no funciona <= IE8)

John Culviner avatar Dec 08 '2014 17:12 John Culviner

Inspirándome en la respuesta de aviv , investigué un poco y esto es lo que se me ocurrió.
No estoy seguro de que sea tan útil según los comentarios en el script y, por supuesto, solo funcionará para navegadores que utilicen un objeto XMLHttpRequest nativo .
Creo que funcionará si se utilizan bibliotecas de JavaScript, ya que utilizarán el objeto nativo si es posible.

function addXMLRequestCallback(callback){
    var oldSend, i;
    if( XMLHttpRequest.callbacks ) {
        // we've already overridden send() so just add the callback
        XMLHttpRequest.callbacks.push( callback );
    } else {
        // create a callback queue
        XMLHttpRequest.callbacks = [callback];
        // store the native send()
        oldSend = XMLHttpRequest.prototype.send;
        // override the native send()
        XMLHttpRequest.prototype.send = function(){
            // process the callback queue
            // the xhr instance is passed into each callback but seems pretty useless
            // you can't tell what its destination is or call abort() without an error
            // so only really good for logging that a request has happened
            // I could be wrong, I hope so...
            // EDIT: I suppose you could override the onreadystatechange handler though
            for( i = 0; i < XMLHttpRequest.callbacks.length; i++ ) {
                XMLHttpRequest.callbacks[i]( this );
            }
            // call the native send()
            oldSend.apply(this, arguments);
        }
    }
}

// e.g.
addXMLRequestCallback( function( xhr ) {
    console.log( xhr.responseText ); // (an empty string)
});
addXMLRequestCallback( function( xhr ) {
    console.dir( xhr ); // have a look if there is anything useful here
});
meouw avatar Mar 05 '2011 09:03 meouw