2016-11-22 71 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