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

如何在Chrome扩展的popup弹窗中展示像素打点的网络请求数据

Chrome扩展自动加载匹配网络请求实现方案

结论先行

该需求必须通过background脚本(Manifest V3规范中为background service worker)实现,核心原因是popup页面仅在用户点击扩展图标时临时存活,关闭后直接销毁,无法在后台持续监听页面产生的网络请求。同时你现有代码中调用的chrome.devtools.network API仅能在DevTools扩展上下文运行,无法在popup页面直接调用,属于无效代码。

实现步骤

  • 配置扩展的manifest.json,声明所需权限和后台服务配置
  • 在background脚本中持续监听网络请求,筛选符合要求的打点请求后存入本地存储
  • 修改popup脚本,在页面初始化时直接读取本地存储的匹配请求数据,自动渲染到页面,无需点击按钮触发

核心代码示例

1. manifest.json(Manifest V3版本,Chrome当前主推规范)

{
  "manifest_version": 3,
  "name": "HCP365 Debugger",
  "version": "1.0.0",
  "permissions": ["webRequest", "storage", "activeTab"],
  "host_permissions": ["*://*.pubnub.com/*"],
  "background": {
    "service_worker": "background.js"
  },
  "action": {
    "default_popup": "popup.html"
  }
}

2. background.js(后台常驻监听)

// 监听所有pubnub域名的请求
chrome.webRequest.onBeforeRequest.addListener(
  (details) => {
    // 筛选publish类型的打点请求
    if (!details.url.includes('/publish/')) return;

    const urlObj = new URL(details.url);
    const pathSegments = urlObj.pathname.split('/');
    // 组装你需要的字段
    const matchedReq = {
      channel: pathSegments[5] || '-',
      message: pathSegments[7] || '-',
      requestUrl: details.url,
      timestamp: new Date().toLocaleString()
    };

    // 将匹配到的请求存入本地存储,最多保留20条避免占用过多空间
    chrome.storage.local.get('matchedReqList', (res) => {
      const newList = [matchedReq, ...(res.matchedReqList || [])].slice(0, 20);
      chrome.storage.local.set({ matchedReqList: newList });
    });
  },
  { urls: ["*://*.pubnub.com/*"] },
  ["requestBody"]
);

3. 修改后的popup.js

const dataContainer = document.getElementById('data');

// popup打开时自动触发数据加载
document.addEventListener('DOMContentLoaded', async () => {
  // 读取本地存储的匹配请求
  chrome.storage.local.get('matchedReqList', (res) => {
    const reqList = res.matchedReqList || [];
    if (reqList.length === 0) {
      dataContainer.innerHTML = '<p class="text-gray-500 text-center">暂无匹配的打点请求</p>';
      return;
    }
    // 渲染请求列表
    dataContainer.innerHTML = reqList.map(item => `
      <div class="border-b border-gray-200 py-3 mb-2">
        <p class="font-bold text-sm">频道:${item.channel}</p>
        <p class="text-xs text-gray-600 mt-1">消息:${item.message}</p>
        <p class="text-xs text-gray-400 mt-1">请求时间:${item.timestamp}</p>
      </div>
    `).join('');
  });
});

// 原有获取当前URL的按钮功能保留即可
document.getElementById('getCurrentURL').addEventListener('click', async () => {
  const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  dataContainer.innerHTML = tab.url;
});

补充说明

  • 若需要获取请求的返回体内容,webRequest API无法直接获取,可改用chrome.debugger API实现,或者在content script中注入监听逻辑捕获页面发出的请求。
  • 可在popup中新增清空按钮,点击后清空本地存储的历史请求列表,避免旧数据干扰。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 13:24:04