拦截网页中ajax请求,在响应前修改数据
版权声明:
本文为博主原创文章,转载请声明原文链接...谢谢。o_0。
更新时间:
2022-10-25 20:16:28
温馨提示:
学无止境,技术类文章有它的时效性,请留意文章更新时间,如发现内容有误请留言指出,防止别人"踩坑",我会及时更新文章
一些原因需要对页面中的ajax请求进行拦截,修改响应内容后再放行。原理为替换(hook)页面中ajax请求对象的请求来响应回调,如下
(function () {
function modifyResponse(response) {
var original_response, modified_response;
if (this.readyState === 4) {
console.log(this.requestURL, this.requestMethod);
// 使用在 openBypass 中保存的相关参数判断是否需要修改
// if (this.requestUrl ... && this.requestMethod ...) {
original_response = response.target.responseText;
Object.defineProperty(this, "responseText", {writable: true});
modified_response = JSON.parse(original_response);
// 根据 sendBypass 中保存的数据修改响应内容
this.responseText = JSON.stringify(modified_response);
// }
}
}
function openBypass(original_function) {
return function (method, url, async) {
// 保存请求相关参数
this.requestMethod = method;
this.requestURL = url;
this.addEventListener("readystatechange", modifyResponse);
return original_function.apply(this, arguments);
};
}
function sendBypass(original_function) {
return function (data) {
// 保存请求相关参数
this.requestData = data;
return original_function.apply(this, arguments);
};
}
XMLHttpRequest.prototype.open = openBypass(XMLHttpRequest.prototype.open);
XMLHttpRequest.prototype.send = sendBypass(XMLHttpRequest.prototype.send);
})();以上代码在页面上执行过后,页面中所有ajax请求都会经过这里