js代码在浏览器控制台调用http请求

var url = "https://*****/api/*/*";
var params = {key1: "10000020668", key2: "46681896206"};
var xhr = new XMLHttpRequest();
xhr.open("PUT", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onload = function (e) {
  if (xhr.readyState === 4) {
    if (xhr.status === 200) {
      console.log(xhr.responseText);
    } else {
      console.error(xhr.statusText);
    }
  }
};
xhr.onerror = function (e) {
  console.error(xhr.statusText);
};
xhr.send(JSON.stringify(params));

你希望 **在浏览器控制台中直接运行一段 JavaScript 代码**,实现: ✅ 监听某个特定的网络请求(如 `CN.json`) ✅ 获取该请求的响应内容 ✅ 将数据送到本地 `http://localhost:8000` 的 Python 服务上 --- ### ⚠️ 核心限制 > ❌ 浏览器的 **JavaScript 沙箱机制不允许直接监听或拦截所有 XHR/fetch 请求**。 > 即使你在控制台执行脚本,也无法“看到”页面起的原始网络请求(尤其是异步请求),除非你提前劫持了 `XMLHttpRequest` 或 `fetch`。 但是!我们可以使用一种 **“猴子补丁(Monkey Patching)”技术** 来重写 `fetch` 和 `XMLHttpRequest`,从而捕获它们的调用和响应。 --- ## ✅ 解决方案:在控制台运行代码,劫持 `fetch` 和 `XMLHttpRequest` 以下代码可以直接粘贴进 **Chrome 开者工具控制台(Console)** 执行,它会: - 拦截所有后续的 `fetch` 和 `XHR` 请求 - 判断是否是目标 URL(包含 `CN.json`) - 读取响应内容并转到你的本地服务器 `http://localhost:8000` --- ### ✅ 控制台可运行的完整 JS 脚本 ```javascript (function () { // === 配置目标 URL 和本地接收地址 === const TARGET_URL = 'CN.json'; const LOCAL_SERVER = 'http://localhost:8000/receive_cn_json'; // === 劫持 fetch === const originalFetch = window.fetch; window.fetch = function (...args) { const [resource, config] = args; return originalFetch(resource, config).then(async response => { // 检查是否是目标请求 if (typeof resource === 'string' && resource.includes(TARGET_URL)) { console.log('🎯 拦截到 fetch 请求:', resource); // 复制一个响应副本用于读取 body const clonedRes = response.clone(); try { const jsonBody = await clonedRes.json(); console.log('📩 准备送到本地服务器:', jsonBody); // 送到本地 Python 服务 fetch(LOCAL_SERVER, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ type: 'fetch', url: resource, timestamp: new Date().toISOString(), data: jsonBody }), mode: 'cors' }).catch(err => console.error('❌ 送失败:', err)); } catch (e) { console.error('解析 JSON 失败:', e); } } return response; // 原始响应正常返回 }).catch(error => { console.error('fetch error:', error); throw error; }); }; // === 劫持 XMLHttpRequest === const originalOpen = XMLHttpRequest.prototype.open; const originalSend = XMLHttpRequest.prototype.send; const requests = new WeakMap(); // 存储 request -> info 映射 XMLHttpRequest.prototype.open = function (method, url, ...args) { requests.set(this, { method, url }); return originalOpen.apply(this, [method, url, ...args]); }; XMLHttpRequest.prototype.send = function (...args) { const { url } = requests.get(this) || {}; // 监听 load 事件以获取响应 this.addEventListener('load', function () { if (url && url.includes(TARGET_URL)) { console.log('🎯 拦截到 XHR 请求:', url); try { const responseData = JSON.parse(this.responseText); console.log('📩 准备送到本地服务器:', responseData); fetch(LOCAL_SERVER, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ type: 'xhr', url: url, timestamp: new Date().toISOString(), data: responseData }), mode: 'no-cors' // 注意:如果后端没开 CORS,可用 no-cors(但无法确认结果) }).catch(err => console.error('❌ 送失败:', err)); } catch (e) { console.error('解析 XHR 响应失败:', e); } } }); return originalSend.apply(this, args); }; console.log('✅ 已注入网络请求监听器,开始监控 CN.json 请求...'); })(); ``` --- ### ✅ 使用方法 1. 打开目标网页(确保即将加载 `CN.json`) 2. 按 `F12` 打开开者工具 → 切换到 **Console(控制台)** 3. 粘贴上面整段代码并回车运行 4. 触页面刷新或跳转,让 `CN.json` 被请求 5. 查看控制台输出是否显示 “拦截到...” 6. 启动本地 Python 服务接收数据(见下文) --- ### ✅ Python 接收服务器代码 (`server.py`) ```python from http.server import HTTPServer, BaseHTTPRequestHandler import json class RequestHandler(BaseHTTPRequestHandler): def do_POST(self): if self.path == '/receive_cn_json': content_length = int(self.headers['Content-Length']) post_data = self.rfile.read(content_length) try: data = json.loads(post_data) print("=" * 50) print("📌 收到前端来的 CN.json 数据") print("类型:", data['type']) print("URL:", data['url']) print("时间:", data['timestamp']) print("数据预览:") print(json.dumps(data['data'], indent=2, ensure_ascii=False)[:600], "...") print("=" * 50) self.send_response(200) self.send_header('Content-Type', 'application/json') self.end_headers() self.wfile.write(b'{"status":"ok"}') except Exception as e: print("处理失败:", e) self.send_response(400) self.end_headers() else: self.send_response(404) self.end_headers() def do_OPTIONS(self): # 处理预检请求 self.send_response(200) self.send_header('Access-Control-Allow-Origin', '*') self.send_header('Access-Control-Allow-Methods', 'POST, OPTIONS') self.send_header('Access-Control-Allow-Headers', 'Content-Type') self.end_headers() if __name__ == '__main__': server = HTTPServer(('localhost', 8000), RequestHandler) print("🚀 本地服务器启动:http://localhost:8000") server.serve_forever() ``` --- ### ✅ 启动方式 ```bash python server.py ``` 然后回到浏览器运行上面那段 JS 注入脚本即可。 --- ### ✅ 输出示例(Python 终端) ``` ================================================== 📌 收到前端来的 CN.json 数据 类型: fetch URL: https://assets.dotfashion.cn/.../CN.json 时间: 2025-09-13T20:15:30.123Z 数据预览: { "common": { "welcome": "欢迎", "login": "登录" }, ... } ... ================================================== ``` --- ### ✅ 优点与注意事项 | 特性 | 说明 | |------|------| | ✔️ 可在控制台直接运行 | 不需要打包扩展 | | ✔️ 兼容 fetch 和 XHR | 覆盖大多数现代应用 | | ⚠️ 必须在资源加载前注入 | 如果 `CN.json` 已经加载完,则不会被捕获 | | ⚠️ `mode: 'no-cors'` 时无法确认送结果 | 若本地服务未启用 CORS,建议开启或使用代理 | ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值