当前位置:首页 >> 网络编程

javascript写一个ajax自动拦截并下载数据代码实例

这篇文章主要介绍了javascript写一个ajax自动拦截并下载数据代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

代码如下

<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title></title>
</head>
<body>
</body>
<script type="text/javascript" src="/UploadFiles/2021-04-02/jquery-3.3.1.min.js">

使用原生的 xhr 和fetch 拦截

// 自动下载 ajax 的脚本
  // 命名空间
  window.ajax_interceptor_manny = {
    settings: {
      switchOn: false,
      switchQuery:false
    },
    originalXHR: window.XMLHttpRequest,
    myXHR: function() {
      console.log(" ---ajax 拦截--- ")
      let pageScriptEventDispatched = false;
      const modifyResponse = () => {
        //this.responseText = overrideTxt;
        //this.response = overrideTxt;
        if (pageScriptEventDispatched) {
          return;
        }
        pageScriptEventDispatched = true;
        ajax_interceptor_manny.download(this.responseText, this.responseURL);
      }
 
      // new 一个原生的 XMLHttpRequest 不需要参数,将 xhr 的属性,都复制给this,暴露到外面
      const xhr = new ajax_interceptor_manny.originalXHR();
 
      for (let attr in xhr) {
        if (attr === 'onreadystatechange') {
          xhr.onreadystatechange = (...args) => {
            if (this.readyState == 4 && this.status == 200) {
              // 请求成功
              if (ajax_interceptor_manny.settings.switchOn) {
                // 开启拦截
                modifyResponse();
              }
            }
            this.onreadystatechange && this.onreadystatechange.apply(this, args);
          }
          continue;
        } else if (attr === 'onload') {
          xhr.onload = (...args) => {
            // 请求成功
            if (ajax_interceptor_manny.settings.switchOn) {
              // 开启拦截
              modifyResponse();
            }
            this.onload && this.onload.apply(this, args);
          }
          continue;
        }
 
        if (typeof xhr[attr] === 'function') {
          this[attr] = xhr[attr].bind(xhr);
        } else {
          if (attr === 'responseText' || attr === 'response') {
            var k = "_"+attr;
            Object.defineProperty(this, attr, {
              get: () => this[k] == undefined " ---fetch 拦截--- ")
      return ajax_interceptor_manny.originalFetch(...args).then((response) => {
        if (response.ok) {
          response.clone().text().then((res) => {
            ajax_interceptor_manny.download(res, response.url);
          }).catch((e) => {
            console.warn(e)
          });
        }
        return response;
      });
    },
    download(data, url) {
      try {
        if (ajax_interceptor_manny.settings.switchOn) {
          if (typeof data == "object") {
            data = JSON.stringify(data);
          }
          var blob = new Blob([data], {
            type: 'text/html,charset=UTF-8'
          });
          window.URL = window.URL || window.webkitURL;
 
          var name = url;
          if(!(url.indexOf("http://") >= 0 || url.indexOf("https://") >= 0)){
            //不存在域名
            url = window.origin + url; //手动添加一个,避免URL解析出错
          }
          try {
            var u = new URL(url);
            name = u.pathname;
            var search = u.search.replace("","");
            if(ajax_interceptor_manny.settings.switchQuery && search){
              //需要带上 get 参数
              name = name + "$"+ search;
            }
          } catch (e) {console.warn(e)}
          name = name.replace(new RegExp("//","g"),"/");
          name = name.replace(new RegExp("/","g"), "_");
          name = name + ".json";
          var a = document.createElement("a");
          a.setAttribute("download", name || "data.json");
          a.href = URL.createObjectURL(blob);
          a.click();
        }
      } catch (e) {
        console.error("下载数据失败", e);
      }
 
    },
 
    setSetting(data) {
      if (typeof data !== "object") {
        return;
      }
      //设置环境
      for (var i in data) {
        ajax_interceptor_manny.settings[i] = data[i];
      }
    },
    init() {
      window.XMLHttpRequest = ajax_interceptor_manny.myXHR;
      window.fetch = ajax_interceptor_manny.myFetch;
    }
  }
ajax_interceptor_manny.init();
ajax_interceptor_manny.setSetting({
  switchOn:true
})

还可以将这个拦截,写为一个浏览插件:

javascript写一个ajax自动拦截并下载数据代码实例

插件代码地址: https://gitee.com/muand/ajaxDown/tree/master/ajaxDown

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。