简介
经常需要对xhr的数据进行抓包或者获取其数据,但是由于xhr的实现方式,我们很难直接hook到xhr的回调函数,这时我们可以使用如下代码,对xhr进行hook来拿到xhr的返回数据。可以用于常见的自动化工具来执行,如phantomjs、selenium、puppeteer、playwright、队长模块、油猴等。  
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 
 | window.hooks_response = [];function addXMLRequestCallback(callback) {
 var oldSend, i;
 if (XMLHttpRequest.callbacks) {
 XMLHttpRequest.callbacks.push(callback);
 } else {
 XMLHttpRequest.callbacks = [callback];
 oldSend = XMLHttpRequest.prototype.send;
 XMLHttpRequest.prototype.send = function () {
 for (i = 0; i < XMLHttpRequest.callbacks.length; i++) {
 XMLHttpRequest.callbacks[i](this);
 }
 oldSend.apply(this, arguments);
 }
 }
 }
 
 function hook_xhr() {
 addXMLRequestCallback(function (xhr) {
 xhr.addEventListener("load", function () {
 if (xhr.readyState == 4 && xhr.status == 200) {
 
 window.hooks_response.push({ 'responseURL': xhr.responseURL, 'responseText': xhr.responseText });
 }
 });
 });
 }
 
 | 
在页面加载前或点击等操作前执行本代码,后续执行 return window.hooks_response 即可获取到xhr的返回数据。