Javascript:覆盖 XMLHttpRequest.open() [英] Javascript: Overriding XMLHttpRequest.open()

查看:18
本文介绍了Javascript:覆盖 XMLHttpRequest.open()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何能够覆盖 XMLHttpRequest.open() 方法,然后捕获并更改它的参数?

How would I be able to override the XMLHttpRequest.open() method and then catch and alter it's arguments?

我已经尝试过代理方法,但它不起作用,尽管在调用 XMLHttpRequest() 时删除了打开覆盖:

I've already tried the proxy method but it didn't work, although removing the open over-rid when XMLHttpRequest() was called:

(function() {
    var proxied = window.XMLHttpRequest.open;
    window.XMLHttpRequest.open = function() {
        $('.log').html(arguments[0]);
        return proxied.apply(this, arguments);
    };
})();

推荐答案

你不是在修改 XMLHttpRequest objects 继承的 open 方法,只是在 XMLHttpRequest objects 中添加一个方法code>XMLHttpRequest 构造函数 实际上从未使用过.

You are not modifying the open method inherited by XMLHttpRequest objects but just adding a method to the XMLHttpRequest constructor which is actually never used.

我在 facebook 中尝试了这段代码,我能够捕捉到请求:

I tried this code in facebook and I was able to catch the requests:

(function() {
    var proxied = window.XMLHttpRequest.prototype.open;
    window.XMLHttpRequest.prototype.open = function() {
        console.log( arguments );
        return proxied.apply(this, [].slice.call(arguments));
    };
})();

/*
    ["POST", "/ajax/chat/buddy_list.php?__a=1", true]
    ["POST", "/ajax/apps/usage_update.php?__a=1", true]
    ["POST", "/ajax/chat/buddy_list.php?__a=1", true]
    ["POST", "/ajax/canvas_ticker.php?__a=1", true]
    ["POST", "/ajax/canvas_ticker.php?__a=1", true]
    ["POST", "/ajax/chat/buddy_list.php?__a=1", true]
*/

所以是的,需要将 open 方法添加到 XMLHttpRequest 原型 (window.XMLHttpRequest.prototype) 而不是 XMLHttpRequest 构造函数 (window.XMLHttpRequest)

So yeah the open method needs to be added to XMLHttpRequest prototype (window.XMLHttpRequest.prototype) not XMLHttpRequest constructor (window.XMLHttpRequest)

这篇关于Javascript:覆盖 XMLHttpRequest.open()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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