本帖最后由 庶民 于 2023-6-13 16:43 编辑
AI
使用Proxy劫持XMLHttpRequest 的响应 (注意:proxy会在频繁通信中降低性能)
// ==UserScript==
// @name XMLHttpRequest Proxy Demo
// @namespace http://tampermonkey-demo/
// @version 1
// @description Intercept XMLHttpRequest responses using Proxy
// @match https://example.com/*
// @grant none
// ==/UserScript==
(function() {
'use strict';
// Create a Proxy object to intercept XMLHttpRequest responses
const responseProxy = new Proxy(XMLHttpRequest.prototype, {
get(target, property, receiver) {
if (property === 'onreadystatechange') {
// Intercept the onreadystatechange event handler
return function() {
const xhr = this;
const oldReadyStateChange = xhr.onreadystatechange;
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
// Intercept the response when readyState is 4 (DONE) and status is 200 (OK)
const responseText = xhr.responseText;
console.log('Intercepted response:', responseText);
// Modify the response as needed
const modifiedResponseText = responseText.replace(/foo/g, 'bar');
// Call the original onreadystatechange event handler with the modified response
oldReadyStateChange.call(xhr, modifiedResponseText);
} else {
// Call the original onreadystatechange event handler for other cases
oldReadyStateChange.call(xhr);
}
};
};
} else {
// Return the original XMLHttpRequest property for other cases
return Reflect.get(target, property, receiver);
}
}
});
// Replace the original XMLHttpRequest with the Proxy object
XMLHttpRequest.prototype = responseProxy;
})();
上面这脚本使用 Proxy 对 XMLHttpRequest.prototype 对象进行劫持,拦截了其 onreadystatechange 属性的读取操作,并返回一个新的函数,该函数会在 XMLHttpRequest 对象的 onreadystatechange 事件触发时被调用。
在这个函数中,我们可以拦截 XMLHttpRequest 的响应,修改它并返回给原始的 onreadystatechange 事件处理程序。
|