You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取其他脚本请求到的JSON数据?

在自定义JavaScript中捕获XHR/Fetch请求的JSON响应

XHR或Fetch请求的响应不会自动存入sessionStorage,除非目标网站主动将数据写入其中。要在自定义JS(比如浏览器扩展)中获取这些JSON响应,核心思路是拦截原生的请求API,在响应返回时捕获数据。以下是两种常用实现方式:

1. 拦截XMLHttpRequest

通过重写原生XMLHttpRequest构造函数,监听请求完成事件来获取JSON数据:

// 保存原生XHR构造函数
const originalXHR = window.XMLHttpRequest;

window.XMLHttpRequest = function() {
  const xhr = new originalXHR();
  // 覆盖原生onload方法
  const originalOnLoad = xhr.onload;
  xhr.onload = function() {
    // 判断响应是否为JSON类型
    const isJsonResponse = 
      xhr.responseType === 'json' || 
      (xhr.getResponseHeader('Content-Type')?.includes('application/json'));
    
    if (isJsonResponse) {
      try {
        const jsonData = xhr.response || JSON.parse(xhr.responseText);
        // 这里处理捕获到的JSON数据,比如打印或传给扩展后台
        console.log('XHR JSON响应:', jsonData);
        // 浏览器扩展中可通过chrome.runtime.sendMessage传递数据到后台
        // chrome.runtime.sendMessage({ type: 'xhr-captured', data: jsonData });
      } catch (err) {
        console.error('解析XHR JSON失败:', err);
      }
    }
    // 执行原生onload逻辑,避免破坏原有页面功能
    if (originalOnLoad) originalOnLoad.call(this);
  };
  return xhr;
};

2. 拦截Fetch API

针对现代网站常用的fetch方法,同样通过重写实现拦截:

const originalFetch = window.fetch;

window.fetch = async function(...args) {
  // 发送原生请求并获取响应
  const response = await originalFetch(...args);
  // 克隆响应(响应流只能读取一次,克隆后不影响原页面使用)
  const clonedResp = response.clone();

  try {
    if (clonedResp.headers.get('Content-Type')?.includes('application/json')) {
      const jsonData = await clonedResp.json();
      console.log('Fetch JSON响应:', jsonData);
      // 扩展中传递数据示例
      // chrome.runtime.sendMessage({ type: 'fetch-captured', data: jsonData });
    }
  } catch (err) {
    console.error('解析Fetch JSON失败:', err);
  }

  // 返回原生响应,保证页面原有逻辑正常运行
  return response;
};

浏览器扩展中的注意事项

如果是在浏览器扩展的内容脚本中使用上述代码,需要注意:

  • 内容脚本运行在隔离上下文,无法直接访问页面的原生window对象,因此需要将拦截代码注入到页面主上下文:
    // 内容脚本中动态注入拦截代码
    const injectScript = document.createElement('script');
    injectScript.textContent = `
      // 这里粘贴上面的XHR或Fetch拦截代码
    `;
    document.documentElement.appendChild(injectScript);
    injectScript.remove();
    
  • 若使用Chrome 110+,也可以通过content_script的world: "MAIN"配置,直接在页面主上下文执行脚本,无需动态注入。

内容的提问来源于stack exchange,提问作者ALT

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 23:57:11