XML Http Request Interceptor

XHR网络请求拦截器

目前為 2023-08-18 提交的版本,檢視 最新版本

此腳本不應該直接安裝,它是一個供其他腳本使用的函式庫。欲使用本函式庫,請在腳本 metadata 寫上: // @require https://update.cn-greasyfork.org/scripts/473361/1237028/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. // ==/UserScript==
  9.  
  10. class XHRIntercept {
  11. /** @type {XHRIntercept} */
  12. static _self
  13.  
  14. /**
  15. * 初始化
  16. * @returns {XHRIntercept}
  17. */
  18. constructor() {
  19. if (XHRIntercept._self) return XHRIntercept._self
  20. XHRIntercept._self = this
  21.  
  22. // 修改EventListener方法
  23. let rawXhrAddEventListener = XMLHttpRequest.prototype.addEventListener
  24. XMLHttpRequest.prototype.addEventListener = function (key, func) {
  25. if (key === "progress") {
  26. this.onprogress = func
  27. } else {
  28. rawXhrAddEventListener.apply(this, arguments)
  29. }
  30. }
  31. let rawXhrRemoveEventListener = XMLHttpRequest.prototype.removeEventListener
  32. XMLHttpRequest.prototype.removeEventListener = function (key, func) {
  33. if (key === "progress") {
  34. this.onprogress = undefined
  35. } else {
  36. rawXhrRemoveEventListener.apply(this, arguments)
  37. }
  38. }
  39.  
  40. // 修改send方法
  41. /** @type {function[]} */
  42. this.sendIntercepts = []
  43. this.rawXhrSend = XMLHttpRequest.prototype.send
  44. XMLHttpRequest.prototype.send = function () { XHRIntercept._self._xhrSend(this, arguments) }
  45. }
  46.  
  47. /**
  48. * 添加Send拦截器
  49. * @param {function} func
  50. */
  51. onSend(func) {
  52. if (this.sendIntercepts.indexOf(func) >= 0) return
  53. this.sendIntercepts.push(func)
  54. }
  55.  
  56. /**
  57. * 删除Send拦截器
  58. * @param {function | undefined} func
  59. */
  60. offSend(func) {
  61. if (typeof func === "function") {
  62. let index = this.sendIntercepts.indexOf(func)
  63. if (index < 0) return
  64. this.sendIntercepts.splice(index, 1)
  65. } else {
  66. this.sendIntercepts = []
  67. }
  68. }
  69.  
  70.  
  71. /**
  72. * 发送拦截器
  73. * @param {XMLHttpRequest} self
  74. * @param {IArguments} args
  75. */
  76. _xhrSend(self, args) {
  77. let complete = () => { this.rawXhrSend.apply(self, args) }
  78. for (let i = 0; i < this.sendIntercepts.length; i++) {
  79. let flag = this.sendIntercepts[i](self, args, complete)
  80. if (flag) return
  81. }
  82. complete()
  83. }
  84. }