覆盖 XMLHttpRequest 的发送方法

2022-01-15 00:00:00 xmlhttprequest javascript

我正在尝试通过重写 XMLHttpRequest.send 函数记录(并稍后修改)XMLHttpRequest 发送到服务器的数据.

I'm trying to log (and later modify) the data XMLHttpRequest sends to a server by overriding XMLHttpRequest.send function.

我的函数将数据正确记录到控制台,但是请求没有完成,因此浏览器会无限期地等待响应.

My function logs the data correctly to the console, however the request doesn't finish, therefore the browser keeps waiting for the response indefinitely.

你知道代码有什么问题吗?

Any ideas what's wrong with the code?

XMLHttpRequest.prototype.realSend = XMLHttpRequest.prototype.send;
var newSend = function(vData) { console.log("data: " + vData); realSend(vData); };
XMLHttpRequest.prototype.send = newSend;

推荐答案

XMLHttpRequest.prototype.realSend = XMLHttpRequest.prototype.send;
// here "this" points to the XMLHttpRequest Object.
var newSend = function(vData) { console.log("data: " + vData); this.realSend(vData); };
XMLHttpRequest.prototype.send = newSend;

相关文章