小编典典

JavaScript:检测AJAX请求

ajax

是否可以通过通用JavaScript(而不是框架)检测网页上的全局AJAX调用(尤其是响应)?

我已经在StackOverflow上审查了“JavaScript检测到AJAX事件 ”
的问题,并尝试将接受的答案的代码修补到我的应用程序中,但是没有用。之前,我从未使用AJAX做任何事情,我还不足以对其进行修改以使其正常工作。

我不需要任何花哨的东西,我只需要检测所有(特定的,实际上,但是我必须先检测所有的AJAX响应,然后将它们修补到IF语句中才能使用)。所以,最终,我想要这样的东西:

if (ajax.response == "certainResponseType"){
    //Code
}

, 例如。

更新: 看来我应该澄清一下,我不是在尝试发送请求-我正在开发内容脚本,并且我需要能够 检测
网页的AJAX请求(不是我自己的请求),因此我可以执行检测到响应时起作用。


阅读 426

收藏
2020-07-26

共1个答案

小编典典

以下是一些代码(通过粘贴到Chrome31.0.1650.63的控制台中进行测试),用于捕获和记录或以其他方式处理ajax请求及其响应:

(function() {
    var proxied = window.XMLHttpRequest.prototype.send;
    window.XMLHttpRequest.prototype.send = function() {
        console.log( arguments );
        //Here is where you can add any code to process the request. 
        //If you want to pass the Ajax request object, pass the 'pointer' below
        var pointer = this
        var intervalId = window.setInterval(function(){
                if(pointer.readyState != 4){
                        return;
                }
                console.log( pointer.responseText );
                //Here is where you can add any code to process the response.
                //If you want to pass the Ajax request object, pass the 'pointer' below
                clearInterval(intervalId);

        }, 1);//I found a delay of 1 to be sufficient, modify it as you need.
        return proxied.apply(this, [].slice.call(arguments));
    };


})();

此代码以可接受的答案解决了上述问题:

请注意,如果使用框架(如jQuery),则可能无法正常工作,因为调用send后它们可能会覆盖onreadystatechange(我认为jQuery确实如此)。或者他们可以覆盖send方法(但这是不可能的)。因此,这是部分解决方案。

因为它不依赖于未更改“ onreadystatechange”回调,而是监视“ readyState”本身。

2020-07-26