Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch any event which is doing http request with javascript

I have my website running some 3rd party app which is doing some http request to inject the data. I want to know if it is possible to catch any http request which is initialized from my page, and how to catch it if it is possible ?

I want to catch that with javascript, because i need to show on my page some hints about http request.

like image 686
Jigberto Avatar asked Jan 13 '23 04:01

Jigberto


1 Answers

I want to catch that with javascript, because i need to show on my page some hints about http request.

You can wrap XMLHttpRequest in a function which logs the caller before returning a real XMLHttpRequest.

(function () { // scope saves you from infinite loops / loss of __xhr
    var __xhr = window.XMLHttpRequest; // back up
    function XMLHttpRequest() { // wrap
        console.log(
            XMLHttpRequest.caller || arguments.caller || 'caller not supported'
        );
        return new __xhr;
    }
    window.XMLHttpRequest = XMLHttpRequest; // shadow
}());

function foo() { // example
    var bar = new XMLHttpRequest();
}
foo(); // invoke

/* console logs
function foo() { // example
    var bar = new XMLHttpRequest();
}
*/

The constructor can be retrieved by

var x = new XMLHttpRequest(); // function doing this gets logged
window.XMLHttpRequest = x.constructor; // normality restored
like image 120
Paul S. Avatar answered Feb 04 '23 17:02

Paul S.