与突出显示来自不同网站的文本不一致

Inconsistency with Highlighting Text from Different Websites

本文关键字:网站 文本 不一致 显示      更新时间:2023-09-26

我使用以下代码来突出显示chrome扩展程序的内容脚本中的"and"一词。

function findText(element, pattern, callback) {
    for (var childi= element.childNodes.length; childi-->0;) {
        var child= element.childNodes[childi];
        if (child.nodeType==1) {
            findText(child, pattern, callback);
        } else if (child.nodeType==3) {
            var matches= [];
            var match;
            while (match= pattern.exec(child.data))
                matches.push(match);
            for (var i= matches.length; i-->0;)
                callback.call(window, child, matches[i]);
        }
    }
}
findText(document.body, /'band'b/g, function(node, match) {
    var span= document.createElement('span');
    span.className= 'highlight';
    node.splitText(match.index+3);
    span.appendChild(node.splitText(match.index));
    node.parentNode.insertBefore(span, node.nextSibling);
});

这段代码成功地在维基百科等页面上突出显示了单词"and",但是当我导航到更复杂的网站(如 espn.com 或 cnn.com(时,它无法突出显示单词"and"。

猜我接近 DOM 树的方式有问题,但无法安静地弄清楚。

通过Chrome扩展程序突出显示页面上的文本必须通过"内容脚本">完成。内容脚本的目的是收集数据或使用CSS/Javascript浏览的页面进行更改。因此,我们需要将 highlight(( 函数放在内容脚本中。

下面是 highlight(( 方法的示例代码:

highlight('yellow');

在内容脚本中,需要侦听来自扩展的请求,以便我们向其发送所选文本:

chrome.extension.onRequest.addListener(function(request, sender,  sendResponse) {
if (request.method == "getSelection")
sendResponse({data: window.getSelection().toString()});
else
sendResponse({}); // snub them.
});