TamperMonkey实现指定接口POST请求Payload或响应体修改方案咨询
用Tampermonkey实现POST请求/响应篡改
完全可以通过Tampermonkey实现你的需求,以下是两种场景的具体实现代码:
一、发送前修改POST请求的Payload
这个方案会在请求发送到服务器前,替换id=someid里的someid为随机值:
// ==UserScript== // @name 修改指定POST请求Payload // @namespace http://tampermonkey.net/ // @version 0.1 // @match https://somesite.com/* // @run-at document-start // @grant none // ==/UserScript== (function() { 'use strict'; // 保存原始XMLHttpRequest的send方法 const originalSend = XMLHttpRequest.prototype.send; XMLHttpRequest.prototype.send = function(data) { // 检查请求目标是否是指定endpoint,且为POST方法 if (this._url === 'https://somesite.com/endpoint' && this._method === 'POST') { // 生成随机ID替换原someid const randomId = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15); // 修改请求数据 data = data.replace(/id=someid/, `id=${randomId}`); } // 调用原始send方法发送修改后的数据 originalSend.call(this, data); }; // 保存请求的URL和方法,用于后续判断 const originalOpen = XMLHttpRequest.prototype.open; XMLHttpRequest.prototype.open = function(method, url) { this._method = method; this._url = url; originalOpen.apply(this, arguments); }; })();
代码说明:
@run-at document-start确保脚本在页面所有JS之前加载,避免错过请求拦截- 重写
open方法记录请求的方法和URL,方便后续匹配目标请求 - 重写
send方法,匹配到指定请求时,替换Payload里的someid为随机生成的字符串
二、返回后修改响应体
如果需要在站点JS处理响应前替换返回的36位字符串,可以用这个方案:
// ==UserScript== // @name 修改指定POST请求响应体 // @namespace http://tampermonkey.net/ // @version 0.1 // @match https://somesite.com/* // @run-at document-start // @grant none // ==/UserScript== (function() { 'use strict'; const originalOpen = XMLHttpRequest.prototype.open; XMLHttpRequest.prototype.open = function(method, url) { this._method = method; this._url = url; originalOpen.apply(this, arguments); }; // 重写XMLHttpRequest的responseText属性 Object.defineProperty(XMLHttpRequest.prototype, 'responseText', { get: function() { // 判断是否是目标请求且已完成 if (this._url === 'https://somesite.com/endpoint' && this._method === 'POST' && this.readyState === 4) { // 生成符合格式的36位随机字符串(xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx) const generateRandomUUID = () => { return 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'.replace(/x/g, function(c) { const r = Math.random() * 16 | 0; return r.toString(16); }); }; return generateRandomUUID(); } // 非目标请求返回原始响应 return this._responseText; }, set: function(value) { this._responseText = value; }, configurable: true }); })();
代码说明:
- 通过重写
responseText的getter,在站点JS读取响应内容时返回我们生成的随机字符串 - 生成的字符串严格遵循原响应的36位带连字符格式,避免触发校验逻辑
额外提示:
如果目标站点使用fetchAPI发起请求,你需要额外重写fetch方法,逻辑和XHR类似,核心都是拦截请求/响应并修改对应内容。
内容的提问来源于stack exchange,提问作者alpacafondue
相关产品推荐
相关产品推荐

