仅限JavaScript:监控页面上的任何AJAX请求 [英] JavaScript Only: Monitor Any AJAX Request on the Page

查看:63
本文介绍了仅限JavaScript:监控页面上的任何AJAX请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的页面中有一些脚本文件因为从其他来源加载到我的页面而无法访问它们。 (解释起来有点复杂)

I have some script files in my page that I can't access them because they load from other sources to my page. (It's a little bit complex to explain)

这些脚本有AJAX请求,所以我想在他们的回复中做一些工作。

Those scripts have AJAX requests, so I want to do some work in their responses.

在JavaScript(不是jQuery)中是否有任何方法可以监控页面上的任何AJAX请求,以便在AJAX完成请求后我可以做些什么?
(那些AJAX请求不在我手中)

Is there any way in JavaScript (Not jQuery) that I can monitor any AJAX requests on the page so I can do something after those AJAX complete their requests?
(Those AJAX requests are not in my hand anyway)

推荐答案

这是我用来劫持的一些原生JavaScript任何XHR(AJAX)请求,你应该能够接受它并运行它(取决于你有多好,哈哈)。我评论了您感兴趣的部分:)

Here is some native JavaScript I use to "hijack" any XHR (AJAX) requests, you should be able to take this and run with it (depends on how good you are, lol). I commented the part you will be interested in :)

var xmlreqc = XMLHttpRequest;
XMLHttpRequest = function ()
{
    try
    {
        this.xhr = new xmlreqc();
        return this;
    }
    catch (e) 
    {
        alert(e.message);
        return null;
    }
};

XMLHttpRequest.prototype.open = function (method, url, async, user, password)
{
    try
    {
        return this.xhr.open(method, url, async, user, password); //send it on
    }
    catch (e) 
    {
        alert(e.message);
        return null;
    }
};

XMLHttpRequest.prototype.setRequestHeader = function (header, value)
{
    try
    {
        this.xhr.setRequestHeader(header, value);
    }
    catch (e) 
    {
        alert(e.message);
    }
};

XMLHttpRequest.prototype.send = function (postBody)
{
    var myXHR = null;
    try
    {
        myXHR = this;
        this.xhr.onreadystatechange = function () { myXHR.onreadystatechangefunction(); };
        this.xhr.send(postBody);
    }
    catch (e) 
    {
        alert(e.message); 
    }
};

XMLHttpRequest.prototype.onreadystatechangefunction = function ()
{
    try
    {
        if (this.xhr.readyState == 4)
        {
            //here you will do whatever you want with the response, then send it onwards as if nothing happened
        }
        this.readyState = this.xhr.readyState;
        this.responseText = this.xhr.responseText;
        this.responseXML = this.xhr.responseXML;
        this.status = this.xhr.status;
        this.statusText = this.xhr.statusText;
    }
    catch (e) 
    {
        alert(e.message);
    }
    this.onreadystatechange();
};

这篇关于仅限JavaScript:监控页面上的任何AJAX请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆