如何在Microsoft Edge控制台中高亮网页指定文本
解决方案:在Edge控制台高亮指定单词集合
你的代码无效的原因在于:
document.body.innerText.matchAll()返回的是文本内容的匹配结果迭代器,不是DOM元素,自然没有style属性可以修改- 修改
$$('a')的代码仅针对页面链接元素,无法匹配所有文本中的目标单词
以下是可以直接在Edge控制台执行的代码,能遍历页面所有文本节点,同时高亮指定的多个单词:
// 定义需要高亮的单词,可自行修改 const targetWords = ['and', 'this', 'that']; // 构建正则:\b 确保匹配完整单词,gi 表示全局匹配+不区分大小写 const highlightRegex = new RegExp(`\\b(${targetWords.join('|')})\\b`, 'gi'); // 递归遍历所有文本节点的处理函数 function highlightTargetWords(node) { // 跳过脚本、样式等不需要处理的节点 if (node.nodeType === Node.SCRIPT_NODE || node.nodeType === Node.STYLE_NODE) return; if (node.nodeType === Node.TEXT_NODE) { const textContent = node.textContent; // 检查当前文本节点是否包含目标单词 if (highlightRegex.test(textContent)) { const wrapper = document.createElement('span'); // 拆分文本,将匹配到的单词用高亮span包裹 textContent.split(highlightRegex).forEach(segment => { if (highlightRegex.test(segment)) { const highlightSpan = document.createElement('span'); // 自定义高亮样式,可按需修改 highlightSpan.style.backgroundColor = 'lime'; highlightSpan.style.padding = '2px 3px'; highlightSpan.style.borderRadius = '2px'; highlightSpan.textContent = segment; wrapper.appendChild(highlightSpan); } else { wrapper.appendChild(document.createTextNode(segment)); } }); // 替换原文本节点为包含高亮元素的容器 node.parentNode.replaceChild(wrapper, node); } } else { // 递归处理子节点 node.childNodes.forEach(child => highlightTargetWords(child)); } } // 启动高亮处理 highlightTargetWords(document.body);
可选调整:
- 如果需要区分大小写,将正则的
gi改为g - 如果不需要匹配完整单词(比如想高亮"sand"里的"and"),去掉正则中的
\b - 可自行修改
highlightSpan.style里的样式,比如边框、颜色等
内容的提问来源于stack exchange,提问作者Derek Jeder
相关产品推荐
相关产品推荐

