如何监视和拦截所有动态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);
};
发布于 2021-07-06 15:34:28
尝试以下操作。显然,它将适用于在执行此代码片段之后进行的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();
https://stackoverflow.com/questions/68272762
复制