如何解决如何监视和拦截所有动态 AJAX 请求并重新发送它们?
如何监控和拦截所有动态 AJAX 请求并重新发送? 我该怎么做?
XMLHttpRequest.prototype.realSend = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.send = function(value) {
this.addEventListener("error",function(){
/*
Need Resend It By XMLHttpRequest In Here
All Resend Request Are Dynamic Generate
Such As "new XMLHttpRequest(this).send()"
Use AJAX Are Also OK
*/
},false);
this.realSend(value);
};
解决方法
尝试以下操作。显然,它适用于在执行此代码段后进行的 AJAX 调用,因此您需要尽快执行它。
我不确切知道您的用例是什么,但请注意,如果错误原因未解决,失败的请求可能会失败 100 万次。使用此代码,每次重试都等于前一次失败。
另请注意,一旦成功,您将需要进行一些修改才能访问嵌套请求的响应。
// PROXY 'open' INSTEAD OF 'send' SO YOU CAN CAPTURE REQUESTS EARLY.
XMLHttpRequest.prototype._open = XMLHttpRequest.prototype.open;
// WE NEED TO TRACK RETRY NUMBER PER REQUEST TO AVOID INFINITE LOOPS.
XMLHttpRequest.prototype._maxRetry = 5;
XMLHttpRequest.prototype._currentRetry = 0;
XMLHttpRequest.prototype.open = function open(...args) {
if (!this._currentRetry) {
console.log('REQUEST CAPTURED.');
}
this.addEventListener('error',() => {
// ABORT PREVIOUS REQUEST.
this.abort();
// CHECK NUMBER OF RETRIES.
if (this._currentRetry >= this._maxRetry) {
console.log('MAX RETRY REACHED.');
return;
}
console.log(`RETRYING ${this._currentRetry} of ${this._maxRetry}.`);
// CREATE NEW REQUEST INSTANCE.
const req = new XMLHttpRequest();
// COPY UPDATED RETRY NUMBERS TO NEW INSTANCE.
req._maxRetry = this._maxRetry;
req._currentRetry = this._currentRetry + 1;
req.responseType = this.responseType;
// SEND NEW REQUEST USING PREVIOUS REQUEST ARGUMENTS.
req.open(...args);
req.send();
});
// CALL ORIGINAL 'open' METHOD.
this._open(...args);
};
const test = new XMLHttpRequest();
test.open('GET','https://asfashdg');
test.send();
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。