2016-11-22 69 views
1

我在寫一個Firefox擴展。我想要瀏覽整個明文,所以不要使用Javascript或圖片來源,並替換某些字符串。目前,我有這樣的:搜索某些字符串的HTML文檔的文本(並替換它們)

var text = document.documentElement.innerHTML; 

var anyRemaining = true; 
do {  
    var index = text.indexOf("search"); 
    if (index != -1) { 
     // This does not just replace the string with something else, 
     // there's complicated processing going on here. I can't use 
     // string.replace(). 
    } else { 
     anyRemaining = false; 
    } 
} while (anyRemaining); 

這工作,但它也將通過非文本元素和HTML例如Javascript,我只希望它做的可見文本。我怎樣才能做到這一點?

我目前正在考慮檢測一個開放的括號,並繼續在下一個閉括號,但可能有更好的方法來做到這一點。

+0

[JavaScript的替換html正文中的文本](http://stackoverflow.com/a/25699092/215552)似乎在做你想做的事... –

+0

Checkout this [texthighlight function](https://github.com/wet-boew) /wet-boew/blob/master/src/plugins/texthighlight/texthighlight.js)和[演示頁面](https://wet-boew.gith ub.io/v4.0-ci/demos/texthighlight/texthighlight-en.html?txthl=avian%20influenza+world+cook+flu-like%20symptoms+Don%27t%20Forget...+causes%20sickness%20in %20birds,%20it%20can%20also%20infect%20people。) – thekodester

+0

您可以嘗試使用element.textContent獲取文本,而不使用HTML而不使用innerHTML –

回答

1

您可以使用XPath來獲取網頁上的所有文本節點,然後做你的搜索/這些節點上的更換:

function replace(search,replacement){ 
 
\t var xpathResult = document.evaluate(
 
\t \t "//*/text()", 
 
\t \t document, 
 
\t \t null, 
 
\t \t XPathResult.ORDERED_NODE_ITERATOR_TYPE, 
 
\t \t null 
 
\t); 
 
\t var results = []; 
 
\t // We store the result in an array because if the DOM mutates 
 
\t // during iteration, the iteration becomes invalid. 
 
\t while(res = xpathResult.iterateNext()) { 
 
\t \t results.push(res); 
 
\t } 
 
\t results.forEach(function(res){ 
 
\t \t res.textContent = res.textContent.replace(search,replacement); 
 
\t }) 
 
} 
 

 
replace(/Hello/g,'Goodbye');
<div class="Hello">Hello world!</div>

+1

該解決方案有效。我只需要通過調用我的處理方法來替換results.forEach()中的行。謝謝! – latias1290

+0

沒問題。我沒有提到這件事,它在Internet Explorer中不受支持。 – Kyle

+0

如果IE是一個問題,您也可以使用TreeWalker實現來獲取此處顯示的文本節點:http://stackoverflow.com/a/10730777/701263 – Kyle

0

您可以使用正則表達式去掉HTML標籤,可能更容易使用javascript函數返回沒有HTML的文本。有關詳細信息,請參閱本: How can get the text of a div tag using only javascript (no jQuery)

+0

我需要替換我找到的文本,所以我需要能夠重新分配HTML內容。我可以使用正則表達式去除HTML標籤,但是這幾乎會破壞一切。 – latias1290