Tampermonkey 拦截 SSO API 响应并自定义返回内容
使用 Tampermonkey 拦截 SSO API 响应并自定义返回内容
本文介绍如何使用 Tampermonkey 脚本拦截 http://sso.yv.dazd.cn/express_index# 页面中的 API 请求,并自定义 API 响应内容,返回 '{name: '1234'}'。
脚本代码
// ==UserScript==
// @name customize sso api response
// @namespace http://tampermonkey-script-example/
// @version 1.0
// @description customize sso api response for http://sso.yv.dazd.cn/express_index#
// @match http://sso.yv.dazd.cn/express_index#
// @grant GM_xmlhttpRequest
// ==/UserScript==
(function() {
'use strict';
// intercept the request to http://sso.yv.dazd.cn/my_menu_list
// and customize the response
GM_xmlhttpRequest({
method: "GET",
url: "http://sso.yv.dazd.cn/my_menu_list",
onload: function(response) {
console.log("original response:", response.responseText);
var customResponse = '{name: '1234'}';
// replace the original response with the custom one
Object.defineProperty(response, 'responseText', {value: customResponse});
console.log("custom response:", response.responseText);
}
});
})();
脚本原理
- 当访问 http://sso.yv.dazd.cn/express_index# 页面时,Tampermonkey 会拦截 http://sso.yv.dazd.cn/my_menu_list 的请求。
- 使用 GM_xmlhttpRequest 发送一个新的请求来获取自定义的响应。
- 在 onload 回调函数中,将原始响应的 responseText 属性替换为自定义的响应内容 '{name: '1234'}'。
- 最后,打印出原始响应和自定义响应以供检查。
应用场景
该脚本可以用于测试或调试 API 响应,或者在特定情况下替换 API 响应以达到特定目的。
注意
- 该脚本仅适用于 Chrome 和 Firefox 浏览器,并需要安装 Tampermonkey 扩展。
- 脚本代码中的 URL 和 API 地址需要根据实际情况进行修改。
- 该脚本可能会影响网页的正常功能,请谨慎使用。
原文地址: https://www.cveoy.top/t/topic/mNGX 著作权归作者所有。请勿转载和采集!