ajaxHookerLatest

ajaxHooker latest version from https://greatest.deepsurf.us/zh-CN/scripts/455943-ajaxhooker

This script should not be not be installed directly. It is a library for other scripts to include with the meta directive // @require https://update.greatest.deepsurf.us/scripts/465643/1421695/ajaxHookerLatest.js

  1. // ==UserScript==
  2. // @name ajaxHooker
  3. // @author cxxjackie
  4. // @version 1.4.3
  5. // @supportURL https://bbs.tampermonkey.net.cn/thread-3284-1-1.html
  6. // ==/UserScript==
  7.  
  8. var ajaxHooker = function() {
  9. 'use strict';
  10. const version = '1.4.3';
  11. const hookInst = {
  12. hookFns: [],
  13. filters: []
  14. };
  15. const win = window.unsafeWindow || document.defaultView || window;
  16. let winAh = win.__ajaxHooker;
  17. const resProto = win.Response.prototype;
  18. const xhrResponses = ['response', 'responseText', 'responseXML'];
  19. const fetchResponses = ['arrayBuffer', 'blob', 'formData', 'json', 'text'];
  20. const fetchInitProps = ['method', 'headers', 'body', 'mode', 'credentials', 'cache', 'redirect',
  21. 'referrer', 'referrerPolicy', 'integrity', 'keepalive', 'signal', 'priority'];
  22. const xhrAsyncEvents = ['readystatechange', 'load', 'loadend'];
  23. const getType = ({}).toString.call.bind(({}).toString);
  24. const getDescriptor = Object.getOwnPropertyDescriptor.bind(Object);
  25. const emptyFn = () => {};
  26. const errorFn = e => console.error(e);
  27. function isThenable(obj) {
  28. return obj && ['object', 'function'].includes(typeof obj) && typeof obj.then === 'function';
  29. }
  30. function catchError(fn, ...args) {
  31. try {
  32. const result = fn(...args);
  33. if (isThenable(result)) return result.then(null, errorFn);
  34. return result;
  35. } catch (err) {
  36. console.error(err);
  37. }
  38. }
  39. function defineProp(obj, prop, getter, setter) {
  40. Object.defineProperty(obj, prop, {
  41. configurable: true,
  42. enumerable: true,
  43. get: getter,
  44. set: setter
  45. });
  46. }
  47. function readonly(obj, prop, value = obj[prop]) {
  48. defineProp(obj, prop, () => value, emptyFn);
  49. }
  50. function writable(obj, prop, value = obj[prop]) {
  51. Object.defineProperty(obj, prop, {
  52. configurable: true,
  53. enumerable: true,
  54. writable: true,
  55. value: value
  56. });
  57. }
  58. function parseHeaders(obj) {
  59. const headers = {};
  60. switch (getType(obj)) {
  61. case '[object String]':
  62. for (const line of obj.trim().split(/[\r\n]+/)) {
  63. const [header, value] = line.split(/\s*:\s*/);
  64. if (!header) break;
  65. const lheader = header.toLowerCase();
  66. headers[lheader] = lheader in headers ? `${headers[lheader]}, ${value}` : value;
  67. }
  68. break;
  69. case '[object Headers]':
  70. for (const [key, val] of obj) {
  71. headers[key] = val;
  72. }
  73. break;
  74. case '[object Object]':
  75. return {...obj};
  76. }
  77. return headers;
  78. }
  79. function stopImmediatePropagation() {
  80. this.ajaxHooker_isStopped = true;
  81. }
  82. class SyncThenable {
  83. then(fn) {
  84. fn && fn();
  85. return new SyncThenable();
  86. }
  87. }
  88. class AHRequest {
  89. constructor(request) {
  90. this.request = request;
  91. this.requestClone = {...this.request};
  92. }
  93. shouldFilter(filters) {
  94. const {type, url, method, async} = this.request;
  95. return filters.length && !filters.find(obj => {
  96. switch (true) {
  97. case obj.type && obj.type !== type:
  98. case getType(obj.url) === '[object String]' && !url.includes(obj.url):
  99. case getType(obj.url) === '[object RegExp]' && !obj.url.test(url):
  100. case obj.method && obj.method.toUpperCase() !== method.toUpperCase():
  101. case 'async' in obj && obj.async !== async:
  102. return false;
  103. }
  104. return true;
  105. });
  106. }
  107. waitForRequestKeys() {
  108. const requestKeys = ['url', 'method', 'abort', 'headers', 'data'];
  109. if (!this.request.async) {
  110. win.__ajaxHooker.hookInsts.forEach(({hookFns, filters}) => {
  111. if (this.shouldFilter(filters)) return;
  112. hookFns.forEach(fn => {
  113. if (getType(fn) === '[object Function]') catchError(fn, this.request);
  114. });
  115. requestKeys.forEach(key => {
  116. if (isThenable(this.request[key])) this.request[key] = this.requestClone[key];
  117. });
  118. });
  119. return new SyncThenable();
  120. }
  121. const promises = [];
  122. win.__ajaxHooker.hookInsts.forEach(({hookFns, filters}) => {
  123. if (this.shouldFilter(filters)) return;
  124. promises.push(Promise.all(hookFns.map(fn => catchError(fn, this.request))).then(() =>
  125. Promise.all(requestKeys.map(key => Promise.resolve(this.request[key]).then(
  126. val => this.request[key] = val,
  127. () => this.request[key] = this.requestClone[key]
  128. )))
  129. ));
  130. });
  131. return Promise.all(promises);
  132. }
  133. waitForResponseKeys(response) {
  134. const responseKeys = this.request.type === 'xhr' ? xhrResponses : fetchResponses;
  135. if (!this.request.async) {
  136. if (getType(this.request.response) === '[object Function]') {
  137. catchError(this.request.response, response);
  138. responseKeys.forEach(key => {
  139. if ('get' in getDescriptor(response, key) || isThenable(response[key])) {
  140. delete response[key];
  141. }
  142. });
  143. }
  144. return new SyncThenable();
  145. }
  146. return Promise.resolve(catchError(this.request.response, response)).then(() =>
  147. Promise.all(responseKeys.map(key => {
  148. const descriptor = getDescriptor(response, key);
  149. if (descriptor && 'value' in descriptor) {
  150. return Promise.resolve(descriptor.value).then(
  151. val => response[key] = val,
  152. () => delete response[key]
  153. );
  154. } else {
  155. delete response[key];
  156. }
  157. }))
  158. );
  159. }
  160. }
  161. const proxyHandler = {
  162. get(target, prop) {
  163. const descriptor = getDescriptor(target, prop);
  164. if (descriptor && !descriptor.configurable && !descriptor.writable && !descriptor.get) return target[prop];
  165. const ah = target.__ajaxHooker;
  166. if (ah && ah.proxyProps) {
  167. if (prop in ah.proxyProps) {
  168. const pDescriptor = ah.proxyProps[prop];
  169. if ('get' in pDescriptor) return pDescriptor.get();
  170. if (typeof pDescriptor.value === 'function') return pDescriptor.value.bind(ah);
  171. return pDescriptor.value;
  172. }
  173. if (typeof target[prop] === 'function') return target[prop].bind(target);
  174. }
  175. return target[prop];
  176. },
  177. set(target, prop, value) {
  178. const descriptor = getDescriptor(target, prop);
  179. if (descriptor && !descriptor.configurable && !descriptor.writable && !descriptor.set) return true;
  180. const ah = target.__ajaxHooker;
  181. if (ah && ah.proxyProps && prop in ah.proxyProps) {
  182. const pDescriptor = ah.proxyProps[prop];
  183. pDescriptor.set ? pDescriptor.set(value) : (pDescriptor.value = value);
  184. } else {
  185. target[prop] = value;
  186. }
  187. return true;
  188. }
  189. };
  190. class XhrHooker {
  191. constructor(xhr) {
  192. const ah = this;
  193. Object.assign(ah, {
  194. originalXhr: xhr,
  195. proxyXhr: new Proxy(xhr, proxyHandler),
  196. resThenable: new SyncThenable(),
  197. proxyProps: {},
  198. proxyEvents: {}
  199. });
  200. xhr.addEventListener('readystatechange', e => {
  201. if (ah.proxyXhr.readyState === 4 && ah.request && typeof ah.request.response === 'function') {
  202. const response = {
  203. finalUrl: ah.proxyXhr.responseURL,
  204. status: ah.proxyXhr.status,
  205. responseHeaders: parseHeaders(ah.proxyXhr.getAllResponseHeaders())
  206. };
  207. const tempValues = {};
  208. for (const key of xhrResponses) {
  209. try {
  210. tempValues[key] = ah.originalXhr[key];
  211. } catch (err) {}
  212. defineProp(response, key, () => {
  213. return response[key] = tempValues[key];
  214. }, val => {
  215. delete response[key];
  216. response[key] = val;
  217. });
  218. }
  219. ah.resThenable = new AHRequest(ah.request).waitForResponseKeys(response).then(() => {
  220. for (const key of xhrResponses) {
  221. ah.proxyProps[key] = {get: () => {
  222. if (!(key in response)) response[key] = tempValues[key];
  223. return response[key];
  224. }};
  225. }
  226. });
  227. }
  228. ah.dispatchEvent(e);
  229. });
  230. xhr.addEventListener('load', e => ah.dispatchEvent(e));
  231. xhr.addEventListener('loadend', e => ah.dispatchEvent(e));
  232. for (const evt of xhrAsyncEvents) {
  233. const onEvt = 'on' + evt;
  234. ah.proxyProps[onEvt] = {
  235. get: () => ah.proxyEvents[onEvt] || null,
  236. set: val => ah.addEvent(onEvt, val)
  237. };
  238. }
  239. for (const method of ['setRequestHeader', 'addEventListener', 'removeEventListener', 'open', 'send']) {
  240. ah.proxyProps[method] = {value: ah[method]};
  241. }
  242. }
  243. toJSON() {} // Converting circular structure to JSON
  244. addEvent(type, event) {
  245. if (type.startsWith('on')) {
  246. this.proxyEvents[type] = typeof event === 'function' ? event : null;
  247. } else {
  248. if (typeof event === 'object' && event !== null) event = event.handleEvent;
  249. if (typeof event !== 'function') return;
  250. this.proxyEvents[type] = this.proxyEvents[type] || new Set();
  251. this.proxyEvents[type].add(event);
  252. }
  253. }
  254. removeEvent(type, event) {
  255. if (type.startsWith('on')) {
  256. this.proxyEvents[type] = null;
  257. } else {
  258. if (typeof event === 'object' && event !== null) event = event.handleEvent;
  259. this.proxyEvents[type] && this.proxyEvents[type].delete(event);
  260. }
  261. }
  262. dispatchEvent(e) {
  263. e.stopImmediatePropagation = stopImmediatePropagation;
  264. defineProp(e, 'target', () => this.proxyXhr);
  265. defineProp(e, 'currentTarget', () => this.proxyXhr);
  266. this.proxyEvents[e.type] && this.proxyEvents[e.type].forEach(fn => {
  267. this.resThenable.then(() => !e.ajaxHooker_isStopped && fn.call(this.proxyXhr, e));
  268. });
  269. if (e.ajaxHooker_isStopped) return;
  270. const onEvent = this.proxyEvents['on' + e.type];
  271. onEvent && this.resThenable.then(onEvent.bind(this.proxyXhr, e));
  272. }
  273. setRequestHeader(header, value) {
  274. this.originalXhr.setRequestHeader(header, value);
  275. if (!this.request) return;
  276. const headers = this.request.headers;
  277. headers[header] = header in headers ? `${headers[header]}, ${value}` : value;
  278. }
  279. addEventListener(...args) {
  280. if (xhrAsyncEvents.includes(args[0])) {
  281. this.addEvent(args[0], args[1]);
  282. } else {
  283. this.originalXhr.addEventListener(...args);
  284. }
  285. }
  286. removeEventListener(...args) {
  287. if (xhrAsyncEvents.includes(args[0])) {
  288. this.removeEvent(args[0], args[1]);
  289. } else {
  290. this.originalXhr.removeEventListener(...args);
  291. }
  292. }
  293. open(method, url, async = true, ...args) {
  294. this.request = {
  295. type: 'xhr',
  296. url: url.toString(),
  297. method: method.toUpperCase(),
  298. abort: false,
  299. headers: {},
  300. data: null,
  301. response: null,
  302. async: !!async
  303. };
  304. this.openArgs = args;
  305. this.resThenable = new SyncThenable();
  306. ['responseURL', 'readyState', 'status', 'statusText', ...xhrResponses].forEach(key => {
  307. delete this.proxyProps[key];
  308. });
  309. return this.originalXhr.open(method, url, async, ...args);
  310. }
  311. send(data) {
  312. const ah = this;
  313. const xhr = ah.originalXhr;
  314. const request = ah.request;
  315. if (!request) return xhr.send(data);
  316. request.data = data;
  317. new AHRequest(request).waitForRequestKeys().then(() => {
  318. if (request.abort) {
  319. if (typeof request.response === 'function') {
  320. Object.assign(ah.proxyProps, {
  321. responseURL: {value: request.url},
  322. readyState: {value: 4},
  323. status: {value: 200},
  324. statusText: {value: 'OK'}
  325. });
  326. xhrAsyncEvents.forEach(evt => xhr.dispatchEvent(new Event(evt)));
  327. }
  328. } else {
  329. xhr.open(request.method, request.url, request.async, ...ah.openArgs);
  330. for (const header in request.headers) {
  331. xhr.setRequestHeader(header, request.headers[header]);
  332. }
  333. xhr.send(request.data);
  334. }
  335. });
  336. }
  337. }
  338. function fakeXHR() {
  339. const xhr = new winAh.realXHR();
  340. if ('__ajaxHooker' in xhr) console.warn('检测到不同版本的ajaxHooker,可能发生冲突!');
  341. xhr.__ajaxHooker = new XhrHooker(xhr);
  342. return xhr.__ajaxHooker.proxyXhr;
  343. }
  344. fakeXHR.prototype = win.XMLHttpRequest.prototype;
  345. Object.keys(win.XMLHttpRequest).forEach(key => fakeXHR[key] = win.XMLHttpRequest[key]);
  346. function fakeFetch(url, options = {}) {
  347. if (!url) return winAh.realFetch.call(win, url, options);
  348. return new Promise(async (resolve, reject) => {
  349. const init = {};
  350. if (getType(url) === '[object Request]') {
  351. for (const prop of fetchInitProps) init[prop] = url[prop];
  352. if (url.body) init.body = await url.arrayBuffer();
  353. url = url.url;
  354. }
  355. url = url.toString();
  356. Object.assign(init, options);
  357. init.method = init.method || 'GET';
  358. init.headers = init.headers || {};
  359. const request = {
  360. type: 'fetch',
  361. url: url,
  362. method: init.method.toUpperCase(),
  363. abort: false,
  364. headers: parseHeaders(init.headers),
  365. data: init.body,
  366. response: null,
  367. async: true
  368. };
  369. const req = new AHRequest(request);
  370. await req.waitForRequestKeys();
  371. if (request.abort) {
  372. if (typeof request.response === 'function') {
  373. const response = {
  374. finalUrl: request.url,
  375. status: 200,
  376. responseHeaders: {}
  377. };
  378. await req.waitForResponseKeys(response);
  379. const key = fetchResponses.find(k => k in response);
  380. let val = response[key];
  381. if (key === 'json' && typeof val === 'object') {
  382. val = catchError(JSON.stringify.bind(JSON), val);
  383. }
  384. const res = new Response(val, {
  385. status: 200,
  386. statusText: 'OK'
  387. });
  388. defineProp(res, 'type', () => 'basic');
  389. defineProp(res, 'url', () => request.url);
  390. resolve(res);
  391. } else {
  392. reject(new DOMException('aborted', 'AbortError'));
  393. }
  394. return;
  395. }
  396. init.method = request.method;
  397. init.headers = request.headers;
  398. init.body = request.data;
  399. winAh.realFetch.call(win, request.url, init).then(res => {
  400. if (typeof request.response === 'function') {
  401. const response = {
  402. finalUrl: res.url,
  403. status: res.status,
  404. responseHeaders: parseHeaders(res.headers)
  405. };
  406. fetchResponses.forEach(key => res[key] = function() {
  407. if (key in response) return Promise.resolve(response[key]);
  408. return resProto[key].call(this).then(val => {
  409. response[key] = val;
  410. return req.waitForResponseKeys(response).then(() => key in response ? response[key] : val);
  411. });
  412. });
  413. }
  414. resolve(res);
  415. }, reject);
  416. });
  417. }
  418. function fakeFetchClone() {
  419. const descriptors = Object.getOwnPropertyDescriptors(this);
  420. const res = winAh.realFetchClone.call(this);
  421. Object.defineProperties(res, descriptors);
  422. return res;
  423. }
  424. winAh = win.__ajaxHooker = winAh || {
  425. version, fakeXHR, fakeFetch, fakeFetchClone,
  426. realXHR: win.XMLHttpRequest,
  427. realFetch: win.fetch,
  428. realFetchClone: resProto.clone,
  429. hookInsts: new Set()
  430. };
  431. if (winAh.version !== version) console.warn('检测到不同版本的ajaxHooker,可能发生冲突!');
  432. win.XMLHttpRequest = winAh.fakeXHR;
  433. win.fetch = winAh.fakeFetch;
  434. resProto.clone = winAh.fakeFetchClone;
  435. winAh.hookInsts.add(hookInst);
  436. return {
  437. hook: fn => hookInst.hookFns.push(fn),
  438. filter: arr => {
  439. if (Array.isArray(arr)) hookInst.filters = arr;
  440. },
  441. protect: () => {
  442. readonly(win, 'XMLHttpRequest', winAh.fakeXHR);
  443. readonly(win, 'fetch', winAh.fakeFetch);
  444. readonly(resProto, 'clone', winAh.fakeFetchClone);
  445. },
  446. unhook: () => {
  447. winAh.hookInsts.delete(hookInst);
  448. if (!winAh.hookInsts.size) {
  449. writable(win, 'XMLHttpRequest', winAh.realXHR);
  450. writable(win, 'fetch', winAh.realFetch);
  451. writable(resProto, 'clone', winAh.realFetchClone);
  452. delete win.__ajaxHooker;
  453. }
  454. }
  455. };
  456. }();