JavaScript命令.replace可以替换任何网页中的文本吗?我想创建一个Chrome扩展程序来替换任何网页中的特定单词以说出其他内容(例如蛋糕而不是饼图).
zet*_*len 10
该.replace方法是一个字符串操作,因此在由DOM Node对象组成的HTML文档上运行操作并不是很简单.
最好的办法去通过每一个节点在DOM和替换文本中它是使用document.createTreeWalker方法来创建一个TreeWalker对象-这是在很多的Chrome扩展程序中使用的做法!
// 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);
}
Run Code Online (Sandbox Code Playgroud)
// the innerHTML property of any DOM node is a string
document.body.innerHTML = document.body.innerHTML.replace(/cake/g,'pie')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1441 次 |
| 最近记录: |