Javascript .replace命令替换页面文本? [英] Javascript .replace command replace page text?
问题描述
JavaScript命令.replace可以替换任何网页中的文本吗?我想创建一个Chrome扩展程序,用来替换任何网页中的特定单词以说出其他内容(例如蛋糕而不是饼图)。
Can the JavaScript command .replace replace text in any webpage? I want to create a Chrome extension that replaces specific words in any webpage to say something else (example cake instead of pie).
推荐答案
.replace
方法是一个字符串操作,因此在由DOM Node对象组成的HTML文档上运行操作并不是很简单。
The .replace
method is a string operation, so it's not immediately simple to run the operation on HTML documents, which are composed of DOM Node objects.
通过DOM中的每个节点并替换其中的文本的最佳方法是使用 document.createTreeWalker 方法创建TreeWalker对象 - 许多Chrome扩展程序中使用的做法!
The best way to go through every node in a DOM and replace text in it is to use the document.createTreeWalker method to create a TreeWalker object--a practice that is used in a number of Chrome extensions!
// create a TreeWalker of all text nodes
var allTextNodes = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT),
// some temp references for performance
tmptxt,
tmpnode,
// compile the RE and cache the replace string, for performance
cakeRE = /cake/g
replaceValue = "pie";
// iterate through all text nodes
while (allTextNodes.nextNode()) {
tmpnode = allTextNodes.currentNode;
tmptxt = tmpnode.nodeValue;
tmpnode.nodeValue = tmptxt.replace(cakeRE, replaceValue);
}
不要使用innerHTML或innerText
Don't use innerHTML or innerText
// the innerHTML property of any DOM node is a string
document.body.innerHTML = document.body.innerHTML.replace(/cake/g,'pie')
- 它通常较慢(特别是在移动设备上)。
- 它有效地删除并替换整个DOM,这是不太棒并且可能有一些副作用:它会破坏JavaScript代码中附加的所有事件侦听器(通过addEventListener或.onxxxx属性)因此部分/完全破坏功能。
- 然而,这是一种常见,快速且非常脏的方式。
- It's generally slower (especially on mobile devices).
- It effectively removes and replaces the entire DOM, which is not awesome and could have some side effects: it destroys all event listeners attached in JavaScript code (via addEventListener or .onxxxx properties) thus breaking the functionality partially/completely.
- This is, however, a common, quick, and very dirty way to do it.
这篇关于Javascript .replace命令替换页面文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!