Hook Ajax

it can hook all ajax

当前为 2021-06-09 提交的版本,查看 最新版本

此脚本不应直接安装。它是供其他脚本使用的外部库,要使用该库请加入元指令 // @require https://update.cn-greasyfork.org/scripts/426753/939008/Hook%20Ajax.js

  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@hook-js/core')) :
  3. typeof define === 'function' && define.amd ? define(['exports', '@hook-js/core'], factory) :
  4. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.$hookAjax = {}, global.core));
  5. }(this, (function (exports, core) { 'use strict';
  6.  
  7. function _arrayWithHoles(arr) {
  8. if (Array.isArray(arr)) return arr;
  9. }
  10.  
  11. function _iterableToArrayLimit(arr, i) {
  12. var _i = arr && (typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]);
  13.  
  14. if (_i == null) return;
  15. var _arr = [];
  16. var _n = true;
  17. var _d = false;
  18.  
  19. var _s, _e;
  20.  
  21. try {
  22. for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) {
  23. _arr.push(_s.value);
  24.  
  25. if (i && _arr.length === i) break;
  26. }
  27. } catch (err) {
  28. _d = true;
  29. _e = err;
  30. } finally {
  31. try {
  32. if (!_n && _i["return"] != null) _i["return"]();
  33. } finally {
  34. if (_d) throw _e;
  35. }
  36. }
  37.  
  38. return _arr;
  39. }
  40.  
  41. function _arrayLikeToArray$1(arr, len) {
  42. if (len == null || len > arr.length) len = arr.length;
  43.  
  44. for (var i = 0, arr2 = new Array(len); i < len; i++) {
  45. arr2[i] = arr[i];
  46. }
  47.  
  48. return arr2;
  49. }
  50.  
  51. function _unsupportedIterableToArray$1(o, minLen) {
  52. if (!o) return;
  53. if (typeof o === "string") return _arrayLikeToArray$1(o, minLen);
  54. var n = Object.prototype.toString.call(o).slice(8, -1);
  55. if (n === "Object" && o.constructor) n = o.constructor.name;
  56. if (n === "Map" || n === "Set") return Array.from(o);
  57. if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$1(o, minLen);
  58. }
  59.  
  60. function _nonIterableRest() {
  61. throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  62. }
  63.  
  64. function _slicedToArray(arr, i) {
  65. return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray$1(arr, i) || _nonIterableRest();
  66. }
  67.  
  68. function _assertThisInitialized(self) {
  69. if (self === void 0) {
  70. throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  71. }
  72.  
  73. return self;
  74. }
  75.  
  76. function _setPrototypeOf(o, p) {
  77. _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
  78. o.__proto__ = p;
  79. return o;
  80. };
  81.  
  82. return _setPrototypeOf(o, p);
  83. }
  84.  
  85. function _inherits(subClass, superClass) {
  86. if (typeof superClass !== "function" && superClass !== null) {
  87. throw new TypeError("Super expression must either be null or a function");
  88. }
  89.  
  90. subClass.prototype = Object.create(superClass && superClass.prototype, {
  91. constructor: {
  92. value: subClass,
  93. writable: true,
  94. configurable: true
  95. }
  96. });
  97. if (superClass) _setPrototypeOf(subClass, superClass);
  98. }
  99.  
  100. function _typeof(obj) {
  101. "@babel/helpers - typeof";
  102.  
  103. if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
  104. _typeof = function _typeof(obj) {
  105. return typeof obj;
  106. };
  107. } else {
  108. _typeof = function _typeof(obj) {
  109. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  110. };
  111. }
  112.  
  113. return _typeof(obj);
  114. }
  115.  
  116. function _possibleConstructorReturn(self, call) {
  117. if (call && (_typeof(call) === "object" || typeof call === "function")) {
  118. return call;
  119. }
  120.  
  121. return _assertThisInitialized(self);
  122. }
  123.  
  124. function _getPrototypeOf(o) {
  125. _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
  126. return o.__proto__ || Object.getPrototypeOf(o);
  127. };
  128. return _getPrototypeOf(o);
  129. }
  130.  
  131. function _classCallCheck(instance, Constructor) {
  132. if (!(instance instanceof Constructor)) {
  133. throw new TypeError("Cannot call a class as a function");
  134. }
  135. }
  136.  
  137. function _defineProperties(target, props) {
  138. for (var i = 0; i < props.length; i++) {
  139. var descriptor = props[i];
  140. descriptor.enumerable = descriptor.enumerable || false;
  141. descriptor.configurable = true;
  142. if ("value" in descriptor) descriptor.writable = true;
  143. Object.defineProperty(target, descriptor.key, descriptor);
  144. }
  145. }
  146.  
  147. function _createClass(Constructor, protoProps, staticProps) {
  148. if (protoProps) _defineProperties(Constructor.prototype, protoProps);
  149. if (staticProps) _defineProperties(Constructor, staticProps);
  150. return Constructor;
  151. }
  152.  
  153. function _defineProperty(obj, key, value) {
  154. if (key in obj) {
  155. Object.defineProperty(obj, key, {
  156. value: value,
  157. enumerable: true,
  158. configurable: true,
  159. writable: true
  160. });
  161. } else {
  162. obj[key] = value;
  163. }
  164.  
  165. return obj;
  166. }
  167.  
  168. function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; }
  169.  
  170. function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
  171.  
  172. function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
  173.  
  174. function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
  175.  
  176. function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
  177. var id = 0;
  178.  
  179. function getUniqueId() {
  180. return id++;
  181. }
  182.  
  183. /**
  184. * Using to intercept ajax request, new Instance to start hook
  185. */
  186. var AjaxInterceptor = /*#__PURE__*/function () {
  187. function AjaxInterceptor() {
  188. _classCallCheck(this, AjaxInterceptor);
  189.  
  190. _defineProperty(this, "urlHooks", {});
  191.  
  192. _defineProperty(this, "responseHooks", {});
  193.  
  194. _defineProperty(this, "sendHooks", {});
  195.  
  196. var _this = this;
  197.  
  198. core.hookReplace(window, 'XMLHttpRequest', function (D) {
  199. return /*#__PURE__*/function (_D) {
  200. _inherits(XMLHttpRequest, _D);
  201.  
  202. var _super = _createSuper(XMLHttpRequest);
  203.  
  204. function XMLHttpRequest() {
  205. var _this2;
  206.  
  207. _classCallCheck(this, XMLHttpRequest);
  208.  
  209. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  210. args[_key] = arguments[_key];
  211. }
  212.  
  213. _this2 = _super.call.apply(_super, [this].concat(args));
  214.  
  215. _defineProperty(_assertThisInitialized(_this2), "id", void 0);
  216.  
  217. _this2.id = getUniqueId();
  218.  
  219. _this2.addEventListener('readystatechange', function () {
  220. if (_this2.readyState == 4 || [200, 304, 201, 202, 203].includes(_this2.state)) {
  221. _this.onResponse(_assertThisInitialized(_this2));
  222. }
  223. });
  224.  
  225. return _this2;
  226. }
  227.  
  228. return XMLHttpRequest;
  229. }(D);
  230. });
  231. core.hook(window.XMLHttpRequest.prototype, 'open', this.getHookedRequestHandler());
  232. core.hook(window.XMLHttpRequest.prototype, 'send', function (origin) {
  233. return origin.before(function (_ref) {
  234. var args = _ref.args,
  235. prevent = _ref.preventDefault;
  236. return _this.onSend(this, args, prevent);
  237. });
  238. });
  239. }
  240.  
  241. _createClass(AjaxInterceptor, [{
  242. key: "getHookedRequestHandler",
  243. value: function getHookedRequestHandler() {
  244. var _this = this;
  245.  
  246. return function (origin) {
  247. return origin.before(function (_ref2) {
  248. var args = _ref2.args,
  249. prevent = _ref2.preventDefault;
  250. return _this.onRequest(this, args, prevent);
  251. });
  252. };
  253. }
  254. }, {
  255. key: "onSend",
  256. value: function onSend(xhr, args, prevent) {
  257. var sendHandlers = this.sendHooks[xhr.id] || [];
  258. var result;
  259.  
  260. var _iterator = _createForOfIteratorHelper(sendHandlers),
  261. _step;
  262.  
  263. try {
  264. for (_iterator.s(); !(_step = _iterator.n()).done;) {
  265. var sendHandler = _step.value;
  266.  
  267. if (typeof sendHandler === 'function') {
  268. var _params = {
  269. args: args,
  270. prevent: prevent
  271. };
  272. result = sendHandler.call(xhr, _params) || result;
  273. }
  274. }
  275. } catch (err) {
  276. _iterator.e(err);
  277. } finally {
  278. _iterator.f();
  279. }
  280.  
  281. this.clearSendHooks(xhr.id);
  282. return result;
  283. }
  284. }, {
  285. key: "onRequest",
  286. value: function onRequest(xhr, args, prevent) {
  287. var _args = _slicedToArray(args, 2),
  288. url = _args[1];
  289.  
  290. var result;
  291.  
  292. for (var hookUrl in this.urlHooks) {
  293. if (new RegExp(hookUrl).test(url)) {
  294. var _params2 = {
  295. args: args,
  296. prevent: prevent
  297. };
  298. var hooks = this.urlHooks[hookUrl];
  299.  
  300. if (typeof hooks.onRequest === 'function') {
  301. result = hooks.onRequest.call(xhr, _params2) || result;
  302. }
  303.  
  304. this.signResponseHooks(xhr.id, hooks);
  305. this.signSendHooks(xhr.id, hooks);
  306. }
  307. }
  308.  
  309. return result;
  310. }
  311. }, {
  312. key: "onResponse",
  313. value: function onResponse(xhr) {
  314. if (xhr.readyState === 4 || [200, 201, 202, 304].includes(xhr.status)) {
  315. var _replace = function _replace(response) {
  316. if (typeof response !== 'string') {
  317. response = JSON.stringify(response);
  318. }
  319.  
  320. Object.defineProperties(xhr, {
  321. response: {
  322. writable: false,
  323. configurable: true,
  324. value: response
  325. },
  326. responseText: {
  327. writable: false,
  328. configurable: true,
  329. value: response
  330. }
  331. });
  332. };
  333.  
  334. var originResponse = ['', 'text'].includes(xhr.responseType) ? xhr.responseText : xhr.response;
  335.  
  336. var _response;
  337.  
  338. try {
  339. _response = JSON.parse(originResponse);
  340. } catch (e) {
  341. _response = originResponse;
  342. }
  343.  
  344. var _params3 = {
  345. response: _response,
  346. originResponse: originResponse,
  347. replace: function replace(response) {
  348. _params3.response = response;
  349. },
  350. define: function define(property, value) {
  351. Object.defineProperty(xhr, property, {
  352. writable: false,
  353. configurable: true,
  354. value: value
  355. });
  356. }
  357. };
  358. var _id = xhr.id;
  359. var targetResponseHooks = this.responseHooks[_id] || [];
  360.  
  361. var _iterator2 = _createForOfIteratorHelper(targetResponseHooks),
  362. _step2;
  363.  
  364. try {
  365. for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
  366. var targetResponseHook = _step2.value;
  367.  
  368. if (targetResponseHook && typeof targetResponseHook === 'function') {
  369. targetResponseHook.call(xhr, _params3);
  370.  
  371. _replace(_params3.response);
  372. }
  373. }
  374. } catch (err) {
  375. _iterator2.e(err);
  376. } finally {
  377. _iterator2.f();
  378. }
  379.  
  380. this.clearResponseHooks(_id);
  381. }
  382. }
  383. }, {
  384. key: "signResponseHooks",
  385. value: function signResponseHooks(id, hooks) {
  386. if (hooks.onResponse && typeof hooks.onResponse === 'function') {
  387. var exists = this.responseHooks[id] || [];
  388. exists.push(hooks.onResponse);
  389. this.responseHooks[id] = exists;
  390. }
  391. }
  392. }, {
  393. key: "signSendHooks",
  394. value: function signSendHooks(id, hooks) {
  395. if (hooks.onSend && typeof hooks.onSend === 'function') {
  396. var exists = this.sendHooks[id] || [];
  397. exists.push(hooks.onSend);
  398. this.sendHooks[id] = exists;
  399. }
  400. }
  401. }, {
  402. key: "clearResponseHooks",
  403. value: function clearResponseHooks(id) {
  404. this.responseHooks[id] = [];
  405. }
  406. }, {
  407. key: "clearSendHooks",
  408. value: function clearSendHooks(id) {
  409. this.sendHooks[id] = [];
  410. }
  411. /**
  412. * Register from url RegExp
  413. * @param url
  414. * @param hooks
  415. */
  416.  
  417. }, {
  418. key: "register",
  419. value: function register(url, hooks) {
  420. this.urlHooks[url] = hooks;
  421. }
  422. }]);
  423.  
  424. return AjaxInterceptor;
  425. }();
  426.  
  427. exports.AjaxInterceptor = AjaxInterceptor;
  428.  
  429. Object.defineProperty(exports, '__esModule', { value: true });
  430.  
  431. })));