// ==UserScript==
// @name 接口出参修改器(Mock Response Modifier)
// @namespace mock-response-modifier
// @version 1.0.1
// @description 拦截页面 fetch/XHR 请求,支持出参替换、字段合并、规则排序、请求出参带入及侧边吸附悬浮面板。
// @match *://*/*
// @run-at document-start
// @grant GM_setValue
// @grant GM_getValue
// @grant unsafeWindow
// @license MIT
// ==/UserScript==
(function () {
'use strict';
const pageWindow = typeof unsafeWindow !== 'undefined' ? unsafeWindow : window;
const RULES_KEY = 'mock_rules_v1';
const LOG_KEY = 'mock_req_log_v1';
const BALL_POSITION_KEY = 'mock_ball_position_v1';
const BALL_SIZE = 48;
const SNAP_WIDTH = 8;
const SNAP_HEIGHT = 68;
const EDGE_GAP = 8;
const BADGE_CSS = 'background:#1677ff;color:#fff;padding:1px 5px;border-radius:3px;font-weight:bold;';
const TAG = '%c[出参修改器]%c ';
let rules = load(RULES_KEY, []);
let reqLog = load(LOG_KEY, []);
if (!Array.isArray(reqLog)) reqLog = [];
if (reqLog.length > 30) {
reqLog = reqLog.slice(-30);
try {
GM_setValue(LOG_KEY, JSON.stringify(reqLog));
} catch (e) {
}
}
const savedBallPosition = load(BALL_POSITION_KEY, null);
let ballSnapSide = savedBallPosition &&
(savedBallPosition.side === 'left' || savedBallPosition.side === 'right')
? savedBallPosition.side
: null;
let ballTopRatio = savedBallPosition && Number.isFinite(Number(savedBallPosition.topRatio))
? Math.max(0, Math.min(1, Number(savedBallPosition.topRatio)))
: 0.8;
let ballExpandedForPanel = false;
let panel = null;
let uiRoot = null;
let ballHost = null;
let ballRoot = null;
let open = false;
let editingRuleId = null;
let toastTimer = null;
let dragState = null;
let ruleDrag = null;
let suppressNextClick = false;
let suppressClickTimer = null;
console.log(TAG + '脚本已注入 document-start,开始劫持页面 fetch/XHR', BADGE_CSS, '');
function load(key, def) {
try {
const v = GM_getValue(key);
return v ? JSON.parse(v) : def;
} catch (e) {
return def;
}
}
function saveRules() {
GM_setValue(RULES_KEY, JSON.stringify(rules));
updateIndicator();
}
function saveLog() {
if (reqLog.length > 30) reqLog = reqLog.slice(-30);
GM_setValue(LOG_KEY, JSON.stringify(reqLog));
}
function matchRule(url, method) {
if (!url) return null;
const m = (method || 'GET').toUpperCase();
for (const r of rules) {
if (!r.enabled) continue;
if (r.method !== '*' && String(r.method || '*').toUpperCase() !== m) continue;
if (!url.includes(r.url)) continue;
try {
JSON.parse(r.body);
} catch (e) {
continue;
}
return r;
}
return null;
}
function deepMerge(target, patch) {
if (Array.isArray(patch)) return patch;
if (patch !== null && typeof patch === 'object') {
const out = target !== null && typeof target === 'object' && !Array.isArray(target)
? target
: {};
for (const k of Object.keys(patch)) {
out[k] = deepMerge(out[k], patch[k]);
}
return out;
}
return patch;
}
const sleep = (ms) =>
ms ? new Promise((resolve) => setTimeout(resolve, ms)) : Promise.resolve();
function recordRequest(url, method, rule) {
const hasEnabledRules = rules.some((r) => Boolean(r.enabled));
const entry = {
url: String(url || ''),
method: String(method || 'GET').toUpperCase(),
time: Date.now(),
status: hasEnabledRules ? (rule ? 'pending' : 'miss') : null,
ruleMode: rule ? rule.mode : null,
ruleId: rule ? rule.id : null
};
reqLog.push(entry);
saveLog();
if (panel) renderLog();
return entry;
}
function updateRequestStatus(entry, status) {
if (!entry) return;
entry.status = status;
saveLog();
if (panel) renderLog();
}
/* ---------------- Hook fetch ---------------- */
const rawFetch = pageWindow.fetch;
pageWindow.fetch = async function (input, init) {
let url = '';
let method = (init && init.method) || 'GET';
if (typeof input === 'string') {
url = input;
} else if (input && typeof input.url === 'string') {
url = input.url;
method = (init && init.method) || input.method || 'GET';
} else if (input && typeof input.href === 'string') {
url = input.href;
}
method = String(method || 'GET').toUpperCase();
const rule = matchRule(url, method);
const logEntry = recordRequest(url, method, rule);
if (!rule) {
const res = rawFetch.apply(this, arguments);
// 异步捕获真实出参,不阻塞页面
Promise.resolve(res)
.then((response) => {
if (!response || typeof response.clone !== 'function') {
return;
}
return response.clone().text().then((text) => {
logEntry.response = text;
saveLog();
if (panel) renderLog();
});
})
.catch(() => {
});
return res;
}
console.log(TAG + '命中 fetch 规则:', BADGE_CSS, '', method, url, '-> 模式:', rule.mode);
try {
await sleep(Math.max(0, Number(rule.delay) || 0));
if (rule.mode === 'replace') {
// 真实请求仍会发出;页面拿到的是下面构造的模拟响应。
// 不等待真实响应,避免网络较慢时影响前端调试流程。
try {
Promise.resolve(rawFetch.apply(this, arguments)).catch((requestError) => {
console.warn(TAG + '整体替换规则对应的真实请求失败(模拟响应仍会返回)', BADGE_CSS, '', requestError);
});
} catch (requestError) {
console.warn(TAG + '整体替换规则对应的真实请求发起失败(模拟响应仍会返回)', BADGE_CSS, '', requestError);
}
logEntry.response = rule.body;
saveLog();
const response = new Response(rule.body, {
status: 200,
statusText: 'OK',
headers: {
'Content-Type': 'application/json; charset=utf-8'
}
});
updateRequestStatus(logEntry, 'replaced');
return response;
}
const res = await rawFetch.apply(this, arguments);
try {
const realData = await res.clone().json();
const merged = deepMerge(realData, JSON.parse(rule.body));
console.log(TAG + 'fetch merge 结果:', BADGE_CSS, '', merged);
logEntry.response = JSON.stringify(merged);
saveLog();
const response = new Response(JSON.stringify(merged), {
status: res.status,
statusText: res.statusText,
headers: {
'Content-Type': 'application/json; charset=utf-8'
}
});
updateRequestStatus(logEntry, 'merged');
return response;
} catch (e) {
updateRequestStatus(logEntry, 'failed');
console.warn(
TAG + 'merge 模式解析真实响应失败,放行原始响应',
BADGE_CSS,
'',
e
);
return res;
}
} catch (e) {
updateRequestStatus(logEntry, 'failed');
throw e;
}
};
/* ---------------- Hook XMLHttpRequest ---------------- */
const RawXHR = pageWindow.XMLHttpRequest;
function PatchedXHR() {
const xhr = new RawXHR();
let rule = null;
let logEntry = null;
let handled = false;
const origOpen = xhr.open;
xhr.open = function (method, url) {
method = String(method || 'GET').toUpperCase();
rule = matchRule(String(url), method);
logEntry = recordRequest(String(url), method, rule);
handled = false;
return origOpen.apply(this, arguments);
};
xhr.addEventListener('readystatechange', function () {
if (xhr.readyState !== 4 || handled) return;
handled = true;
// 在改写响应前捕获真实出参
const rawText = readXhrRawText(xhr);
if (rawText && logEntry) {
logEntry.response = rawText;
saveLog();
if (panel) renderLog();
}
if (!rule) return;
try {
const patched = patchXhrResponse(xhr, rule);
if (patched) {
updateRequestStatus(
logEntry,
rule.mode === 'replace' ? 'replaced' : 'merged'
);
} else {
updateRequestStatus(logEntry, 'failed');
}
} catch (e) {
updateRequestStatus(logEntry, 'failed');
console.warn(TAG + 'XHR 出参修改失败', BADGE_CSS, '', e);
}
});
return xhr;
}
PatchedXHR.UNSENT = RawXHR.UNSENT;
PatchedXHR.OPENED = RawXHR.OPENED;
PatchedXHR.HEADERS_RECEIVED = RawXHR.HEADERS_RECEIVED;
PatchedXHR.LOADING = RawXHR.LOADING;
PatchedXHR.DONE = RawXHR.DONE;
pageWindow.XMLHttpRequest = PatchedXHR;
function readXhrRawText(xhr) {
try {
if (xhr.responseType === '' || xhr.responseType === 'text') {
return xhr.responseText || '';
}
if (xhr.responseType === 'json') {
return xhr.response == null
? ''
: JSON.stringify(xhr.response);
}
} catch (e) {
}
return '';
}
function patchXhrResponse(xhr, rule) {
let body = rule.body;
if (rule.mode === 'merge') {
let realData;
try {
if (xhr.responseType === 'json') {
realData = xhr.response;
} else if (xhr.responseType === '' || xhr.responseType === 'text') {
const raw = xhr.responseText;
if (!raw) return false;
realData = JSON.parse(raw);
} else {
return false;
}
body = JSON.stringify(deepMerge(realData, JSON.parse(rule.body)));
} catch (e) {
return false;
}
}
const isJsonType = xhr.responseType === 'json';
let jsonVal;
let jsonParsed = false;
try {
jsonVal = JSON.parse(body);
jsonParsed = true;
} catch (e) {
}
const props = {
responseText: {
configurable: true,
get: () => body
},
response: {
configurable: true,
get: () => (isJsonType && jsonParsed ? jsonVal : body)
}
};
if (rule.mode === 'replace') {
props.status = {
configurable: true,
get: () => 200
};
props.statusText = {
configurable: true,
get: () => 'OK'
};
}
let patched = false;
for (const [key, descriptor] of Object.entries(props)) {
try {
Object.defineProperty(xhr, key, descriptor);
if (key === 'response' || key === 'responseText') {
patched = true;
}
} catch (e) {
}
}
if (rule.mode === 'replace' && patched) {
console.log(TAG + '已替换 XHR 出参:', BADGE_CSS, '', rule.method, rule.url);
} else if (patched) {
console.log(
TAG + '已合并 XHR 出参:',
BADGE_CSS,
'',
rule.method,
rule.url,
isJsonType ? jsonVal : body
);
}
return patched;
}
/* ---------------- Floating button and dragging ---------------- */
function whenBodyReady(cb) {
if (document.body) return cb();
const t = setInterval(() => {
if (document.body) {
clearInterval(t);
cb();
}
}, 200);
}
whenBodyReady(() => {
ballHost = document.createElement('div');
Object.assign(ballHost.style, {
position: 'fixed',
right: '20px',
bottom: '20px',
zIndex: '2147483647',
width: `${BALL_SIZE}px`,
height: `${BALL_SIZE}px`
});
ballRoot = ballHost.attachShadow({mode: 'open'});
ballRoot.innerHTML = `
`;
const bubble = ballRoot.querySelector('.bubble');
bubble.addEventListener('pointerdown', onBallPointerDown);
bubble.addEventListener('click', (event) => {
if (suppressNextClick) {
suppressNextClick = false;
event.preventDefault();
event.stopPropagation();
return;
}
// 点击吸附竖条:临时展开成 M 按钮并打开面板;关闭面板后恢复竖条。
if (ballSnapSide && !ballExpandedForPanel) {
ballExpandedForPanel = true;
applySnappedBallPosition(true);
togglePanel();
return;
}
togglePanel();
});
window.addEventListener('pointermove', onBallPointerMove, true);
window.addEventListener('pointerup', onBallPointerUp, true);
window.addEventListener('pointercancel', onBallPointerUp, true);
window.addEventListener('pointermove', onRuleDragMove, true);
window.addEventListener('pointerup', onRuleDragUp, true);
window.addEventListener('pointercancel', onRuleDragUp, true);
window.addEventListener('resize', () => {
if (ballSnapSide) applySnappedBallPosition(false);
else clampBallToViewport();
positionPanel();
});
document.body.appendChild(ballHost);
if (ballSnapSide) applySnappedBallPosition(false);
updateIndicator();
});
function updateIndicator() {
if (!ballRoot) return;
const bubble = ballRoot.querySelector('.bubble');
if (!bubble) return;
const active = rules.some((r) => Boolean(r.enabled));
bubble.classList.toggle('has-enabled-rules', active);
bubble.classList.toggle('no-enabled-rules', !active);
const title = active
? '接口出参修改器:有启用规则'
: '接口出参修改器:没有启用规则';
bubble.title = title;
bubble.setAttribute('aria-label', title);
}
function onBallPointerDown(event) {
if (event.button !== 0) return;
const rect = ballHost.getBoundingClientRect();
dragState = {
pointerId: event.pointerId,
startX: event.clientX,
startY: event.clientY,
left: rect.left,
top: rect.top,
moved: false
};
}
function getVisibleViewport() {
const root = document.documentElement;
return {
// clientWidth excludes the classic vertical scrollbar, so the handle
// remains inside the visible page area instead of sitting underneath it.
width: Math.max(1, root && root.clientWidth || window.innerWidth),
height: Math.max(1, root && root.clientHeight || window.innerHeight)
};
}
function setBallTransition(enabled) {
if (!ballHost) return;
ballHost.style.transition = enabled
? 'left .18s ease, top .18s ease, width .16s ease, height .16s ease'
: 'none';
}
function updateBallVisual() {
if (!ballRoot) return;
const bubble = ballRoot.querySelector('.bubble');
if (!bubble) return;
bubble.classList.toggle('edge-snapped', Boolean(ballSnapSide && !ballExpandedForPanel));
}
function saveBallPosition() {
GM_setValue(BALL_POSITION_KEY, JSON.stringify({
side: ballSnapSide,
topRatio: ballTopRatio
}));
}
function applySnappedBallPosition(animate = false) {
if (!ballHost || !ballSnapSide) return;
const viewport = getVisibleViewport();
const height = ballExpandedForPanel ? BALL_SIZE : SNAP_HEIGHT;
const width = ballExpandedForPanel ? BALL_SIZE : SNAP_WIDTH;
const trackHeight = Math.max(0, viewport.height - SNAP_HEIGHT - EDGE_GAP * 2);
const barTop = EDGE_GAP + ballTopRatio * trackHeight;
const top = ballExpandedForPanel
? barTop + (SNAP_HEIGHT - BALL_SIZE) / 2
: barTop;
const left = ballSnapSide === 'left'
? EDGE_GAP
: viewport.width - EDGE_GAP - width;
setBallTransition(animate);
Object.assign(ballHost.style, {
width: `${width}px`,
height: `${height}px`,
left: `${left}px`,
top: `${Math.max(EDGE_GAP, Math.min(top, viewport.height - height - EDGE_GAP))}px`,
right: 'auto',
bottom: 'auto'
});
updateBallVisual();
if (animate) {
setTimeout(() => {
if (ballHost && !dragState) ballHost.style.transition = '';
}, 240);
}
}
function onBallPointerMove(event) {
if (!dragState || event.pointerId !== dragState.pointerId || !ballHost) {
return;
}
const dx = event.clientX - dragState.startX;
const dy = event.clientY - dragState.startY;
if (!dragState.moved && Math.hypot(dx, dy) < 4) return;
if (!dragState.moved) {
dragState.moved = true;
// 从竖条开始拖动时,先展开成完整按钮,并把鼠标保持在按钮附近。
if (ballSnapSide && !ballExpandedForPanel) {
const side = ballSnapSide;
const viewport = getVisibleViewport();
const left = side === 'left'
? EDGE_GAP
: viewport.width - EDGE_GAP - BALL_SIZE;
const top = Math.max(
EDGE_GAP,
Math.min(event.clientY - BALL_SIZE / 2, viewport.height - BALL_SIZE - EDGE_GAP)
);
ballHost.style.width = `${BALL_SIZE}px`;
ballHost.style.height = `${BALL_SIZE}px`;
ballHost.style.left = `${left}px`;
ballHost.style.top = `${top}px`;
ballHost.style.right = 'auto';
ballHost.style.bottom = 'auto';
ballSnapSide = null;
ballExpandedForPanel = false;
updateBallVisual();
// 重设拖动基准,避免竖条展开成按钮时产生位置跳跃。
dragState.startX = event.clientX;
dragState.startY = event.clientY;
dragState.left = left;
dragState.top = top;
} else if (ballSnapSide && ballExpandedForPanel) {
// 面板打开时拖动已展开的 M 按钮,就从吸附状态脱离。
ballSnapSide = null;
ballExpandedForPanel = false;
updateBallVisual();
}
setBallTransition(false);
const bubble = ballRoot && ballRoot.querySelector('.bubble');
if (bubble) bubble.classList.add('dragging');
}
const left = dragState.left + (event.clientX - dragState.startX);
const top = dragState.top + (event.clientY - dragState.startY);
ballHost.style.left = `${left}px`;
ballHost.style.top = `${top}px`;
ballHost.style.right = 'auto';
ballHost.style.bottom = 'auto';
clampBallToViewport();
positionPanel();
event.preventDefault();
}
function onBallPointerUp(event) {
if (
!dragState ||
(event.pointerId !== undefined && event.pointerId !== dragState.pointerId)
) {
return;
}
const didMove = dragState.moved;
dragState = null;
const bubble = ballRoot && ballRoot.querySelector('.bubble');
if (bubble) bubble.classList.remove('dragging');
if (didMove) {
suppressNextClick = true;
if (suppressClickTimer) clearTimeout(suppressClickTimer);
suppressClickTimer = setTimeout(() => {
suppressNextClick = false;
}, 350);
snapBallToSide();
}
}
function snapBallToSide() {
if (!ballHost) return;
const viewport = getVisibleViewport();
const rect = ballHost.getBoundingClientRect();
// 只有距离屏幕左右边缘 20px 以内才吸附
const SNAP_THRESHOLD = 20;
const distanceLeft = rect.left;
const distanceRight = viewport.width - rect.right;
// 两侧都不够近:保持 M 按钮原位置,不吸附
if (Math.min(distanceLeft, distanceRight) > SNAP_THRESHOLD) {
ballSnapSide = null;
ballExpandedForPanel = false;
// 确保恢复为完整 M 按钮
setBallTransition(true);
ballHost.style.width = `${BALL_SIZE}px`;
ballHost.style.height = `${BALL_SIZE}px`;
updateBallVisual();
saveBallPosition();
positionPanel();
setTimeout(() => {
if (ballHost && !dragState) {
ballHost.style.transition = '';
}
}, 240);
return;
}
// 靠近哪一侧,就吸附到哪一侧
ballSnapSide = distanceLeft <= distanceRight ? 'left' : 'right';
ballExpandedForPanel = false;
const centerY = rect.top + rect.height / 2;
const maxTop = Math.max(
EDGE_GAP,
viewport.height - SNAP_HEIGHT - EDGE_GAP
);
const top = Math.max(
EDGE_GAP,
Math.min(centerY - SNAP_HEIGHT / 2, maxTop)
);
const trackHeight = Math.max(
1,
viewport.height - SNAP_HEIGHT - EDGE_GAP * 2
);
ballTopRatio = Math.max(
0,
Math.min(1, (top - EDGE_GAP) / trackHeight)
);
applySnappedBallPosition(true);
saveBallPosition();
positionPanel();
}
function clampBallToViewport() {
if (!ballHost) return;
const viewport = getVisibleViewport();
const rect = ballHost.getBoundingClientRect();
const maxLeft = Math.max(EDGE_GAP, viewport.width - rect.width - EDGE_GAP);
const maxTop = Math.max(EDGE_GAP, viewport.height - rect.height - EDGE_GAP);
const left = Math.min(maxLeft, Math.max(EDGE_GAP, rect.left));
const top = Math.min(maxTop, Math.max(EDGE_GAP, rect.top));
ballHost.style.left = `${left}px`;
ballHost.style.top = `${top}px`;
ballHost.style.right = 'auto';
ballHost.style.bottom = 'auto';
}
function positionPanel() {
if (!panel || !ballHost || !uiRoot) return;
const viewport = getVisibleViewport();
const ballRect = ballHost.getBoundingClientRect();
const shell = uiRoot.querySelector('.shell');
if (!shell) return;
const gap = 12;
const edge = EDGE_GAP;
// 面板宽度不超过可见网页区域,并为侧边吸附预留向内展开的空间。
let maxWidth = Math.min(560, viewport.width - edge * 2);
if (ballSnapSide === 'left') {
maxWidth = Math.min(maxWidth, viewport.width - ballRect.right - gap - edge);
} else if (ballSnapSide === 'right') {
maxWidth = Math.min(maxWidth, ballRect.left - gap - edge);
}
panel.style.width = `${Math.max(160, maxWidth)}px`;
// 恢复自然高度后再计算面板应放在按钮上方还是下方。
shell.style.maxHeight = '';
const naturalHeight = panel.getBoundingClientRect().height;
const spaceAbove = Math.max(0, ballRect.top - gap - edge);
const spaceBelow = Math.max(0, viewport.height - ballRect.bottom - gap - edge);
let placeAbove;
let availableSpace;
if (naturalHeight <= spaceAbove) {
placeAbove = true;
availableSpace = spaceAbove;
} else if (naturalHeight <= spaceBelow) {
placeAbove = false;
availableSpace = spaceBelow;
} else {
placeAbove = spaceAbove >= spaceBelow;
availableSpace = placeAbove ? spaceAbove : spaceBelow;
}
if (naturalHeight > availableSpace) {
shell.style.maxHeight = `${Math.max(0, availableSpace)}px`;
}
const panelRect = panel.getBoundingClientRect();
const panelWidth = panelRect.width;
let left;
if (ballSnapSide === 'left') {
left = ballRect.right + gap;
} else if (ballSnapSide === 'right') {
left = ballRect.left - gap - panelWidth;
} else {
// 未吸附时,面板右侧尽量与悬浮按钮右侧对齐。
left = ballRect.right - panelWidth + 4;
}
left = Math.max(edge, Math.min(left, viewport.width - panelWidth - edge));
const proposedTop = placeAbove
? ballRect.top - gap - panelRect.height
: ballRect.bottom + gap;
const maxTop = Math.max(edge, viewport.height - panelRect.height - edge);
const top = Math.max(edge, Math.min(proposedTop, maxTop));
panel.style.left = `${left}px`;
panel.style.top = `${top}px`;
panel.style.right = 'auto';
panel.style.bottom = 'auto';
}
/* ---------------- Management panel ---------------- */
function togglePanel() {
if (open) {
if (panel) panel.remove();
panel = null;
uiRoot = null;
open = false;
editingRuleId = null;
if (toastTimer) clearTimeout(toastTimer);
if (ballSnapSide && ballExpandedForPanel) {
ballExpandedForPanel = false;
applySnappedBallPosition(true);
}
return;
}
open = true;
panel = document.createElement('div');
Object.assign(panel.style, {
position: 'fixed',
left: '8px',
top: '8px',
zIndex: '2147483646',
width: 'min(560px, calc(100vw - 32px))',
maxHeight: 'calc(100vh - 16px)'
});
uiRoot = panel.attachShadow({mode: 'open'});
uiRoot.innerHTML = `
接口出参修改器
生效规则
0
按列表顺序匹配,命中第一条
+
新增规则
点击展开
最近请求
0