我认为,为了拦截<条码>XMLHttpRequest的回复,将采用一种更现代的解决办法,将原XMLHttpRequest和在<条码>>>>上将其搁置。 反对:
const { interceptXhrResponse } = (function () {
let interceptionRules = [];
/**
* Function to intercept responses for given URL patterns
* @param {RegExp} urlPattern - Regular expression to match the (canonicalized) URL
* @param {Function} responseHandler - Function to handle the intercepted response
*/
function interceptXhrResponse(urlPattern, responseHandler) {
interceptionRules.push({ urlPattern, responseHandler });
}
// Function to find specific handler for the URL and return modified response
function handleInterceptedResponse(response, url) {
const interceptionRule = interceptionRules.find(({ urlPattern }) =>
urlPattern.test(url)
);
if (interceptionRule) {
const { responseHandler } = interceptionRule;
return responseHandler(response, url);
}
return response;
}
const OriginalXMLHttpRequest = window.XMLHttpRequest;
class XMLHttpRequest extends OriginalXMLHttpRequest {
get responseText() {
// If the request is not done, return the original responseText
if (this.readyState !== 4) {
return super.responseText;
}
return handleInterceptedResponse(super.responseText, this.responseURL);
}
get response() {
// If the request is not done, return the original response
if (this.readyState !== 4) {
return super.response;
}
return handleInterceptedResponse(super.response, this.responseURL);
}
}
window.XMLHttpRequest = XMLHttpRequest;
return { interceptXhrResponse };
})();
上限代码显示<代码>interceptXhrResponse<>code>功能,使您能够以定期表述和相应的回复手写明URL型号。 你可以把你想要的手里的东西回去,改变对策。
例如:
interceptXhrResponse(/.+/, (response, url) => {
return `Response of ${url}: Intercepted. Original response length: ${String(response).length}`
})
然后,我们可以尝试启动XMLHttpRequest
:
const xhr = new XMLHttpRequest()
xhr.open( GET , https://stackoverflow.com/404 )
xhr.send()
xhr.onloadend = () => {
console.log(xhr.responseText)
}
产出:
Response of https://stackoverflow.com/404: Intercepted. Original response length: 63486