Hook Ajax

it can hook all ajax

Stan na 09-06-2021. Zobacz najnowsza wersja.

Ten skrypt nie powinien być instalowany bezpośrednio. Jest to biblioteka dla innych skyptów do włączenia dyrektywą meta // @require https://update.greasyfork.org/scripts/426753/939008/Hook%20Ajax.js

Aby zainstalować ten skrypt, wymagana jest instalacje jednego z następujących rozszerzeń: Tampermonkey, Greasemonkey lub Violentmonkey.

Aby zainstalować ten skrypt, wymagana jest instalacje jednego z następujących rozszerzeń: Tampermonkey, Violentmonkey.

Aby zainstalować ten skrypt, wymagana jest instalacje jednego z następujących rozszerzeń: Tampermonkey, Violentmonkey.

Aby zainstalować ten skrypt, wymagana będzie instalacja rozszerzenia Tampermonkey lub Userscripts.

You will need to install an extension such as Tampermonkey to install this script.

Aby zainstalować ten skrypt, musisz zainstalować rozszerzenie menedżera skryptów użytkownika.

(Mam już menedżera skryptów użytkownika, pozwól mi to zainstalować!)

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

Będziesz musiał zainstalować rozszerzenie menedżera stylów użytkownika, aby zainstalować ten styl.

Będziesz musiał zainstalować rozszerzenie menedżera stylów użytkownika, aby zainstalować ten styl.

Musisz zainstalować rozszerzenie menedżera stylów użytkownika, aby zainstalować ten styl.

(Mam już menedżera stylów użytkownika, pozwól mi to zainstalować!)

(function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@hook-js/core')) :
  typeof define === 'function' && define.amd ? define(['exports', '@hook-js/core'], factory) :
  (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.$hookAjax = {}, global.core));
}(this, (function (exports, core) { 'use strict';

  function _arrayWithHoles(arr) {
    if (Array.isArray(arr)) return arr;
  }

  function _iterableToArrayLimit(arr, i) {
    var _i = arr && (typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]);

    if (_i == null) return;
    var _arr = [];
    var _n = true;
    var _d = false;

    var _s, _e;

    try {
      for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) {
        _arr.push(_s.value);

        if (i && _arr.length === i) break;
      }
    } catch (err) {
      _d = true;
      _e = err;
    } finally {
      try {
        if (!_n && _i["return"] != null) _i["return"]();
      } finally {
        if (_d) throw _e;
      }
    }

    return _arr;
  }

  function _arrayLikeToArray$1(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;
  }

  function _unsupportedIterableToArray$1(o, minLen) {
    if (!o) return;
    if (typeof o === "string") return _arrayLikeToArray$1(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$1(o, minLen);
  }

  function _nonIterableRest() {
    throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  }

  function _slicedToArray(arr, i) {
    return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray$1(arr, i) || _nonIterableRest();
  }

  function _assertThisInitialized(self) {
    if (self === void 0) {
      throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
    }

    return self;
  }

  function _setPrototypeOf(o, p) {
    _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
      o.__proto__ = p;
      return o;
    };

    return _setPrototypeOf(o, p);
  }

  function _inherits(subClass, superClass) {
    if (typeof superClass !== "function" && superClass !== null) {
      throw new TypeError("Super expression must either be null or a function");
    }

    subClass.prototype = Object.create(superClass && superClass.prototype, {
      constructor: {
        value: subClass,
        writable: true,
        configurable: true
      }
    });
    if (superClass) _setPrototypeOf(subClass, superClass);
  }

  function _typeof(obj) {
    "@babel/helpers - typeof";

    if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
      _typeof = function _typeof(obj) {
        return typeof obj;
      };
    } else {
      _typeof = function _typeof(obj) {
        return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
      };
    }

    return _typeof(obj);
  }

  function _possibleConstructorReturn(self, call) {
    if (call && (_typeof(call) === "object" || typeof call === "function")) {
      return call;
    }

    return _assertThisInitialized(self);
  }

  function _getPrototypeOf(o) {
    _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
      return o.__proto__ || Object.getPrototypeOf(o);
    };
    return _getPrototypeOf(o);
  }

  function _classCallCheck(instance, Constructor) {
    if (!(instance instanceof Constructor)) {
      throw new TypeError("Cannot call a class as a function");
    }
  }

  function _defineProperties(target, props) {
    for (var i = 0; i < props.length; i++) {
      var descriptor = props[i];
      descriptor.enumerable = descriptor.enumerable || false;
      descriptor.configurable = true;
      if ("value" in descriptor) descriptor.writable = true;
      Object.defineProperty(target, descriptor.key, descriptor);
    }
  }

  function _createClass(Constructor, protoProps, staticProps) {
    if (protoProps) _defineProperties(Constructor.prototype, protoProps);
    if (staticProps) _defineProperties(Constructor, staticProps);
    return Constructor;
  }

  function _defineProperty(obj, key, value) {
    if (key in obj) {
      Object.defineProperty(obj, key, {
        value: value,
        enumerable: true,
        configurable: true,
        writable: true
      });
    } else {
      obj[key] = value;
    }

    return obj;
  }

  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; } } }; }

  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); }

  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; }

  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); }; }

  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; } }
  var id = 0;

  function getUniqueId() {
    return id++;
  }

  /**
   * Using to intercept ajax request, new Instance to start hook
   */
  var AjaxInterceptor = /*#__PURE__*/function () {
    function AjaxInterceptor() {
      _classCallCheck(this, AjaxInterceptor);

      _defineProperty(this, "urlHooks", {});

      _defineProperty(this, "responseHooks", {});

      _defineProperty(this, "sendHooks", {});

      var _this = this;

      core.hookReplace(window, 'XMLHttpRequest', function (D) {
        return /*#__PURE__*/function (_D) {
          _inherits(XMLHttpRequest, _D);

          var _super = _createSuper(XMLHttpRequest);

          function XMLHttpRequest() {
            var _this2;

            _classCallCheck(this, XMLHttpRequest);

            for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
              args[_key] = arguments[_key];
            }

            _this2 = _super.call.apply(_super, [this].concat(args));

            _defineProperty(_assertThisInitialized(_this2), "id", void 0);

            _this2.id = getUniqueId();

            _this2.addEventListener('readystatechange', function () {
              if (_this2.readyState == 4 || [200, 304, 201, 202, 203].includes(_this2.state)) {
                _this.onResponse(_assertThisInitialized(_this2));
              }
            });

            return _this2;
          }

          return XMLHttpRequest;
        }(D);
      });
      core.hook(window.XMLHttpRequest.prototype, 'open', this.getHookedRequestHandler());
      core.hook(window.XMLHttpRequest.prototype, 'send', function (origin) {
        return origin.before(function (_ref) {
          var args = _ref.args,
              prevent = _ref.preventDefault;
          return _this.onSend(this, args, prevent);
        });
      });
    }

    _createClass(AjaxInterceptor, [{
      key: "getHookedRequestHandler",
      value: function getHookedRequestHandler() {
        var _this = this;

        return function (origin) {
          return origin.before(function (_ref2) {
            var args = _ref2.args,
                prevent = _ref2.preventDefault;
            return _this.onRequest(this, args, prevent);
          });
        };
      }
    }, {
      key: "onSend",
      value: function onSend(xhr, args, prevent) {
        var sendHandlers = this.sendHooks[xhr.id] || [];
        var result;

        var _iterator = _createForOfIteratorHelper(sendHandlers),
            _step;

        try {
          for (_iterator.s(); !(_step = _iterator.n()).done;) {
            var sendHandler = _step.value;

            if (typeof sendHandler === 'function') {
              var _params = {
                args: args,
                prevent: prevent
              };
              result = sendHandler.call(xhr, _params) || result;
            }
          }
        } catch (err) {
          _iterator.e(err);
        } finally {
          _iterator.f();
        }

        this.clearSendHooks(xhr.id);
        return result;
      }
    }, {
      key: "onRequest",
      value: function onRequest(xhr, args, prevent) {
        var _args = _slicedToArray(args, 2),
            url = _args[1];

        var result;

        for (var hookUrl in this.urlHooks) {
          if (new RegExp(hookUrl).test(url)) {
            var _params2 = {
              args: args,
              prevent: prevent
            };
            var hooks = this.urlHooks[hookUrl];

            if (typeof hooks.onRequest === 'function') {
              result = hooks.onRequest.call(xhr, _params2) || result;
            }

            this.signResponseHooks(xhr.id, hooks);
            this.signSendHooks(xhr.id, hooks);
          }
        }

        return result;
      }
    }, {
      key: "onResponse",
      value: function onResponse(xhr) {
        if (xhr.readyState === 4 || [200, 201, 202, 304].includes(xhr.status)) {
          var _replace = function _replace(response) {
            if (typeof response !== 'string') {
              response = JSON.stringify(response);
            }

            Object.defineProperties(xhr, {
              response: {
                writable: false,
                configurable: true,
                value: response
              },
              responseText: {
                writable: false,
                configurable: true,
                value: response
              }
            });
          };

          var originResponse = ['', 'text'].includes(xhr.responseType) ? xhr.responseText : xhr.response;

          var _response;

          try {
            _response = JSON.parse(originResponse);
          } catch (e) {
            _response = originResponse;
          }

          var _params3 = {
            response: _response,
            originResponse: originResponse,
            replace: function replace(response) {
              _params3.response = response;
            },
            define: function define(property, value) {
              Object.defineProperty(xhr, property, {
                writable: false,
                configurable: true,
                value: value
              });
            }
          };
          var _id = xhr.id;
          var targetResponseHooks = this.responseHooks[_id] || [];

          var _iterator2 = _createForOfIteratorHelper(targetResponseHooks),
              _step2;

          try {
            for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
              var targetResponseHook = _step2.value;

              if (targetResponseHook && typeof targetResponseHook === 'function') {
                targetResponseHook.call(xhr, _params3);

                _replace(_params3.response);
              }
            }
          } catch (err) {
            _iterator2.e(err);
          } finally {
            _iterator2.f();
          }

          this.clearResponseHooks(_id);
        }
      }
    }, {
      key: "signResponseHooks",
      value: function signResponseHooks(id, hooks) {
        if (hooks.onResponse && typeof hooks.onResponse === 'function') {
          var exists = this.responseHooks[id] || [];
          exists.push(hooks.onResponse);
          this.responseHooks[id] = exists;
        }
      }
    }, {
      key: "signSendHooks",
      value: function signSendHooks(id, hooks) {
        if (hooks.onSend && typeof hooks.onSend === 'function') {
          var exists = this.sendHooks[id] || [];
          exists.push(hooks.onSend);
          this.sendHooks[id] = exists;
        }
      }
    }, {
      key: "clearResponseHooks",
      value: function clearResponseHooks(id) {
        this.responseHooks[id] = [];
      }
    }, {
      key: "clearSendHooks",
      value: function clearSendHooks(id) {
        this.sendHooks[id] = [];
      }
      /**
       * Register from url RegExp
       * @param url
       * @param hooks
       */

    }, {
      key: "register",
      value: function register(url, hooks) {
        this.urlHooks[url] = hooks;
      }
    }]);

    return AjaxInterceptor;
  }();

  exports.AjaxInterceptor = AjaxInterceptor;

  Object.defineProperty(exports, '__esModule', { value: true });

})));