Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/246.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 与突出显示来自不同网站的文本不一致_Javascript_Google Chrome Extension_Highlight - Fatal编程技术网

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

Javascript 与突出显示来自不同网站的文本不一致,javascript,google-chrome-extension,highlight,Javascript,Google Chrome Extension,Highlight,我正在使用以下代码突出显示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(

我正在使用以下代码突出显示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);
});
这段代码成功地在维基百科等页面上突出显示了“和”一词,但当我浏览到espn.com或cnn.com等更复杂的网站时,它没有突出显示“和”一词


我猜我接近DOM树的方式有问题,但我无法安静地找出它

通过Chrome扩展突出显示页面上的文本必须通过。内容脚本的目的是收集数据或使用CSS/Javascript对正在浏览的页面进行更改。所以我们需要在内容脚本中放入highlight()函数

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

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

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

我明白。我认为我遇到的问题是,我的代码遇到了更复杂的HTML问题。我需要以某种方式深入HTML,以查找和修改文本周围的HTML标记。如果你能帮上忙,我将不胜感激!
chrome.extension.onRequest.addListener(function(request, sender,  sendResponse) {
if (request.method == "getSelection")
sendResponse({data: window.getSelection().toString()});
else
sendResponse({}); // snub them.
});