全局拦截各种http请求

http请求无非就是ajax、src、href、表单

 function hookAJAX() {
    XMLHttpRequest.prototype.nativeOpen = XMLHttpRequest.prototype.open;
    var customizeOpen = function (method, url, async, user, password) {
      // do something
      this.nativeOpen(method, url, async, user, password);
    };

    XMLHttpRequest.prototype.open = customizeOpen;
  }

  /**
   *全局拦截Image的图片请求添加token
   *
   */
  function hookImg() {
    const property = Object.getOwnPropertyDescriptor(Image.prototype, 'src');
    const nativeSet = property.set;

    function customiseSrcSet(url) {
      // do something
      nativeSet.call(this, url);
    }
    Object.defineProperty(Image.prototype, 'src', {
      set: customiseSrcSet,
    });
  }

  /**
   * 拦截全局open的url添加token
   *
   */
  function hookOpen() {
    const nativeOpen = window.open;
    window.open = function (url) {
      // do something
      nativeOpen.call(this, url);
    };
  }

  function hookFetch() {
    var fet = Object.getOwnPropertyDescriptor(window, 'fetch')
    Object.defineProperty(window, 'fetch', {
      value: function (a, b, c) {
        // do something
        return fet.value.apply(this, args)
      }
    })
  }

猜你喜欢

转载自www.cnblogs.com/amiezhang/p/9984690.html