XHR_INTERCEPTOR

XHR请求拦截工具类

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

  1. // ==UserScript==
  2. // @name XHR_INTERCEPTOR
  3. // @version 1.0.0
  4. // @description XHR请求拦截工具类
  5. // @author Zosah
  6. // ==/UserScript==
  7.  
  8. class XMRInterceptor {
  9. constructor() {
  10. if (XMRInterceptor.instance) {
  11. return XMRInterceptor.instance;
  12. }
  13. this.interceptors = [];
  14. XMRInterceptor.instance = this;
  15. }
  16.  
  17. addUrlInterceptor(item) {
  18. this.interceptors.push(item);
  19. }
  20.  
  21. execute() {
  22. function xhrInterceptor(callback) {
  23. // send拦截
  24. let oldSend = null;
  25. // 在xhr函数下创建一个回调
  26. XMLHttpRequest.callbacks = function (xhr) {
  27. //调用劫持函数,填入一个function的回调函数
  28. //回调函数监听了对xhr调用了监听load状态,并且在触发的时候再次调用一个function,进行一些数据的劫持以及修改
  29. xhr.addEventListener("load", function () {
  30. if (xhr.readyState == 4 && xhr.status == 200) {
  31. callback(xhr);
  32. }
  33. });
  34. };
  35. //获取xhr的send函数,并对其进行劫持
  36. oldSend = XMLHttpRequest.prototype.send;
  37. XMLHttpRequest.prototype.send = function () {
  38. XMLHttpRequest.callbacks(this);
  39. //由于我们获取了send函数的引用,并且复写了send函数,这样我们在调用原send的函数的时候,需要对其传入引用,而arguments是传入的参数
  40. oldSend.apply(this, arguments);
  41. };
  42. }
  43. xhrInterceptor((xhr) => {
  44. for (const item of this.interceptors) {
  45. const url = xhr.responseURL.split(item.domain)[1];
  46. if (url.indexOf(item.url) !== -1) {
  47. item.cb(JSON.parse(xhr.response));
  48. }
  49. }
  50. });
  51. }
  52. }