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

如何改进监听Chrome网络请求日志并检测URL关键词的脚本?

如何改进监听Chrome网络请求日志并检测URL关键词的脚本?

嘿,我来帮你梳理下当前脚本存在的问题,然后给你几个实用的改进方案~

首先先说说原脚本的几个明显问题:

  • 每个资源请求(包括图片、CSS、JS这些静态资源)都会触发弹窗,哪怕是不匹配关键词的请求也会弹“Tracciamenti non implementati!”,这会导致页面疯狂弹框,体验极差
  • 没有去重逻辑,比如页面加载多个带adform的请求,会重复弹出相同的提示
  • PerformanceObserver监听resource类型范围太广,很多不是你真正关心的请求(比如静态资源)都会被捕获,没必要

改进后的网页脚本版本

这个版本解决了上面的问题,还增加了一些实用功能:

// 存储已检测到的关键词,避免重复弹窗
const detectedKeywords = new Set();
// 可自定义的关键词列表,方便后续扩展
const targetKeywords = ["adform", "doubleclick"];

function monitorNetworkRequests() {
  // 先检查浏览器是否支持PerformanceObserver
  if (!window.PerformanceObserver) {
    alert("你的浏览器不支持PerformanceObserver,无法监听网络请求");
    return;
  }

  const observer = new PerformanceObserver((list) => {
    const entries = list.getEntriesByType("resource");
    
    entries.forEach((entry) => {
      // 过滤掉静态资源,只关注可能带追踪的请求(可根据需求调整)
      const staticResourceTypes = ["img", "css", "font"];
      if (staticResourceTypes.includes(entry.initiatorType)) {
        return;
      }

      const url = entry.name.toLowerCase();
      // 遍历关键词列表检查匹配
      for (const keyword of targetKeywords) {
        if (url.includes(keyword) && !detectedKeywords.has(keyword)) {
          detectedKeywords.add(keyword);
          showPopup(`Tracciamenti di ${keyword} implementati!`);
        }
      }
    });
  });

  try {
    observer.observe({ 
      type: "resource", 
      buffered: true,
      // 监听所有资源类型,后续通过initiatorType过滤
      entryTypes: ["resource"]
    });
  } catch (err) {
    console.error("监听网络请求失败:", err);
    alert("监听网络请求时发生错误,请查看控制台");
  }
}

function showPopup(message) {
  const popup = document.createElement("div");
  popup.innerText = message;
  popup.style.position = "fixed";
  popup.style.top = "50%";
  popup.style.left = "50%";
  popup.style.transform = "translate(-50%, -50%)";
  popup.style.backgroundColor = "rgba(0, 0, 0, 0.8)";
  popup.style.color = "white";
  popup.style.padding = "20px";
  popup.style.borderRadius = "8px";
  popup.style.fontSize = "16px";
  popup.style.zIndex = "10000";
  // 增加关闭按钮,提升用户体验
  const closeBtn = document.createElement("button");
  closeBtn.innerText = "X";
  closeBtn.style.position = "absolute";
  closeBtn.style.top = "8px";
  closeBtn.style.right = "12px";
  closeBtn.style.background = "none";
  closeBtn.style.border = "none";
  closeBtn.style.color = "white";
  closeBtn.style.cursor = "pointer";
  closeBtn.addEventListener("click", () => popup.remove());
  
  popup.appendChild(closeBtn);
  document.body.appendChild(popup);

  // 自动移除弹窗的时间延长到5秒,给用户足够时间查看
  setTimeout(() => {
    if (popup.parentNode) popup.remove();
  }, 5000);
}

// 页面加载完成后启动监听
window.addEventListener("load", monitorNetworkRequests);

针对未来Chrome扩展的优化思路

如果之后要做成Chrome扩展,不建议用PerformanceObserver,因为内容脚本的权限有限,而且容易受页面环境影响。Chrome提供了专门的chrome.devtools.network API,能更精准地监听和过滤网络请求:

  1. 扩展结构需要包含devtools.html和对应的脚本
  2. 使用chrome.devtools.network.onRequestFinished.addListener来监听每个完成的请求
  3. 可以直接在DevTools面板里添加自定义面板,或者弹出提示,体验更原生

举个简单的扩展核心代码示例:

// 扩展的devtools脚本
chrome.devtools.network.onRequestFinished.addListener((request) => {
  const url = request.request.url.toLowerCase();
  const targetKeywords = ["adform", "doubleclick"];
  
  for (const keyword of targetKeywords) {
    if (url.includes(keyword)) {
      // 在DevTools控制台打印提示,或者自定义弹窗
      console.log(`检测到${keyword}追踪请求:`, url);
      // 也可以通过chrome.notifications创建系统通知
      chrome.notifications.create({
        type: "basic",
        iconUrl: "icon.png",
        title: "检测到追踪请求",
        message: `发现${keyword}的URL: ${url}`
      });
    }
  }
});

这样做的好处是完全脱离页面环境,不会被页面的JS影响,而且能获取更详细的请求信息(比如请求头、响应内容等)。

备注:内容来源于stack exchange,提问作者AndMM

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.15 09:23:01