XML Http Request Interceptor

XHR网络请求拦截器

此脚本不应直接安装,它是一个供其他脚本使用的外部库。如果您需要使用该库,请在脚本元属性加入:// @require https://update.cn-greasyfork.org/scripts/473361/1237032/XML%20Http%20Request%20Interceptor.js

  1. // ==UserScript==
  2. // @name XML Http Request Interceptor
  3. // @namespace xml-http-request-interceptor
  4. // @version 1.0.0
  5. // @description XHR网络请求拦截器
  6. // @author 如梦Nya
  7. // @license MIT
  8. // @match *://*/*
  9. // ==/UserScript==
  10.  
  11. class XHRIntercept {
  12. /** @type {XHRIntercept} */
  13. static _self
  14.  
  15. /**
  16. * 初始化
  17. * @returns {XHRIntercept}
  18. */
  19. constructor() {
  20. if (XHRIntercept._self) return XHRIntercept._self
  21. XHRIntercept._self = this
  22.  
  23. // 修改EventListener方法
  24. let rawXhrAddEventListener = XMLHttpRequest.prototype.addEventListener
  25. XMLHttpRequest.prototype.addEventListener = function (key, func) {
  26. if (key === "progress") {
  27. this.onprogress = func
  28. } else {
  29. rawXhrAddEventListener.apply(this, arguments)
  30. }
  31. }
  32. let rawXhrRemoveEventListener = XMLHttpRequest.prototype.removeEventListener
  33. XMLHttpRequest.prototype.removeEventListener = function (key, func) {
  34. if (key === "progress") {
  35. this.onprogress = undefined
  36. } else {
  37. rawXhrRemoveEventListener.apply(this, arguments)
  38. }
  39. }
  40.  
  41. // 修改send方法
  42. /** @type {function[]} */
  43. this.sendIntercepts = []
  44. this.rawXhrSend = XMLHttpRequest.prototype.send
  45. XMLHttpRequest.prototype.send = function () { XHRIntercept._self._xhrSend(this, arguments) }
  46. }
  47.  
  48. /**
  49. * 添加Send拦截器
  50. * @param {function} func
  51. */
  52. onSend(func) {
  53. if (this.sendIntercepts.indexOf(func) >= 0) return
  54. this.sendIntercepts.push(func)
  55. }
  56.  
  57. /**
  58. * 删除Send拦截器
  59. * @param {function | undefined} func
  60. */
  61. offSend(func) {
  62. if (typeof func === "function") {
  63. let index = this.sendIntercepts.indexOf(func)
  64. if (index < 0) return
  65. this.sendIntercepts.splice(index, 1)
  66. } else {
  67. this.sendIntercepts = []
  68. }
  69. }
  70.  
  71.  
  72. /**
  73. * 发送拦截器
  74. * @param {XMLHttpRequest} self
  75. * @param {IArguments} args
  76. */
  77. _xhrSend(self, args) {
  78. let complete = () => { this.rawXhrSend.apply(self, args) }
  79. for (let i = 0; i < this.sendIntercepts.length; i++) {
  80. let flag = this.sendIntercepts[i](self, args, complete)
  81. if (flag) return
  82. }
  83. complete()
  84. }
  85. }