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

Edge扩展网页文本高亮功能失效求助:函数未触发排查

问题分析

你当前的代码有两个核心问题:

  • popup的JS运行在独立的隔离上下文,操作的是popup自身的DOM,不是当前网页的内容,所以你的查找逻辑根本没作用到目标页面上。
  • 你查看的是网页的控制台,但console.log输出在popup的控制台里(右键popup选「检查」才能看到)。
修复方案

1. 更新manifest.json

保持manifest v2的前提下,确保权限和结构正确,我们会用activeTab权限动态注入脚本:

{
  "manifest_version": 2,
  "name": "Find and Follow",
  "version": "1.0",
  "description": "A browser extension that allows you to search for text and follow hyperlinks with ease.",
  "browser_action": {
    "default_popup": "popup.html"
  },
  "permissions": ["activeTab"]
}

2. 重写popup.js

让popup点击按钮后,向当前活跃标签页注入执行高亮逻辑的脚本:

document.getElementById("find").addEventListener("click", () => {
  const searchText = document.getElementById("search").value.trim();
  if (!searchText) return;

  // 向当前页面注入高亮脚本
  chrome.tabs.executeScript({
    code: `
      // 先清除之前的高亮
      document.querySelectorAll('.highlighted-text').forEach(el => {
        const parent = el.parentNode;
        parent.replaceChild(el.firstChild, el);
        parent.normalize();
      });

      const searchText = ${JSON.stringify(searchText)};
      const regex = new RegExp(searchText, 'ig');
      const walker = document.createTreeWalker(
        document.body,
        NodeFilter.SHOW_TEXT,
        null,
        false
      );

      let node;
      while (node = walker.nextNode()) {
        // 跳过脚本和样式标签内的文本
        if (node.parentNode.tagName === 'SCRIPT' || node.parentNode.tagName === 'STYLE') continue;
        const matches = node.nodeValue.match(regex);
        if (matches) {
          const fragment = document.createDocumentFragment();
          let lastIndex = 0;
          node.nodeValue.replace(regex, (match, index) => {
            fragment.appendChild(document.createTextNode(node.nodeValue.slice(lastIndex, index)));
            const span = document.createElement('span');
            span.className = 'highlighted-text';
            span.style.backgroundColor = 'yellow';
            span.textContent = match;
            fragment.appendChild(span);
            lastIndex = index + match.length;
          });
          fragment.appendChild(document.createTextNode(node.nodeValue.slice(lastIndex)));
          node.parentNode.replaceChild(fragment, node);
        }
      }
    `
  });
});

3. 方案说明

  • 用chrome.tabs.executeScript将代码注入到当前网页的上下文,才能真正操作网页DOM。
  • 采用TreeWalker遍历文本节点的方式,避免直接替换innerHTML导致页面事件绑定失效、样式破坏等问题。
  • 增加了清除历史高亮的逻辑,避免重复搜索后高亮叠加。
验证方法
  • 加载扩展后,打开任意网页,在popup输入搜索词点击Find。
  • 右键popup选择「检查」,可查看popup的控制台输出;网页的控制台能看到注入脚本的执行情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 01:14:57