使用javascript捕获正在执行http请求的任何事件

Jig*_*rto 2 javascript javascript-events

我的网站运行了一些第三方应用程序正在做一些http请求来注入数据.我想知道是否可以捕获从我的页面初始化的任何http请求,以及如果可能的话如何捕获它?

我想用javascript捕获它,因为我需要在我的页面上显示一些关于http请求的提示.

Pau*_* S. 8

我想用javascript捕获它,因为我需要在我的页面上显示一些关于http请求的提示.

您可以将XMLHttpRequest包装在一个函数中,该函数在返回真正的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();
}
*/
Run Code Online (Sandbox Code Playgroud)

可以通过检索构造函数

var x = new XMLHttpRequest(); // function doing this gets logged
window.XMLHttpRequest = x.constructor; // normality restored
Run Code Online (Sandbox Code Playgroud)