XMLHttpRequest 拦截包括两部分
- 请求(request)拦截
- 请求完(response)拦截
直接上代码
<script>
class XMLHttp {
request = function (param) {};
response = function (param) {};
}
let http = new XMLHttp();
function initXMLHttpRequest() {
let open = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function(...args){
let send = this.send;
let _this = this
let post_data = []
this.send = function (...data) {
post_data = data;
return send.apply(_this, data)
}
http.request(args)
this.addEventListener('readystatechange', function () {
if (this.readyState === 4) {
let config = {
url: args[1],
status: this.status,
method: args[0],
data: post_data
}
http.response({config, response: this.response})
}
}, false)
return open.apply(this, args);
}
}
(function () {
http.request = function (param) {
};
http.response = function (res) {
console.log(res, "---response");
}
initXMLHttpRequest();
})();
</script>