2016-02-16 14 views
0

我正在使用以下代碼突出顯示我的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樹時出現了一些問題,但無法安靜地弄清楚它。

回答

-1

通過Chrome擴展程序在頁面上突出顯示文本必須通過'Content Script'完成。內容腳本的目的是收集數據或對使用CSS/Javascript瀏覽的頁面進行更改。所以我們需要在內容腳本中加入highlight()函數。

這裏有一個亮點的樣本代碼()方法:

highlight('yellow'); 

在你的內容腳本,你要聽從你的擴展來的請求,讓我們選定的文本發送:

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

我明白這一點。我認爲我遇到的問題是我的代碼遇到了更復雜的HTML問題。我需要以某種方式進一步滲透到HTML中以查找和修改文本週圍的HTML標記。如果你能提供幫助,將不勝感激! – Lance

相關問題