问题
I'm writing a JavaScript for an open source browser available for Android to replace the text in the body tag of the pages loaded into the browser with some different text.
This should be worked in away that once a page get loaded into the browser, this JavaScript executes & the replacements take place & finally the page with replaced text is visible in the browser.
This is the replacing part of the code:
var textnodes, node, i;
textnodes = document.evaluate("//body//text()[not(ancestor::script) and not(ancestor::style)]",document,null,XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,null);
replace();
function replace() {
for (i = 0; i < textnodes.snapshotLength; i++) {
node = textnodes.snapshotItem(i);
text = node.data;
text = text.replace(/\'/g, "♥");
//The rest of the replacements
node.data = text;
}
}
However document.evaluate
seems to be not working. Can anyone help me to correct this code or any suggestions to do this replacing body text task in any other way?
Thanks!
回答1:
Sorry, you don't get DOM Level 3 XPath in the Android browser.
Whilst you can use a JavaScript XPath implementation (eg), that's going to be a slow and bulky solution compared to writing specific DOM traversal code.
function replaceInTextNodes(parent, needle, replacement) {
for (var child= parent.firstChild; child!==null; child= child.nextSibling) {
if (child.nodeType===1) { # Node.ELEMENT_NODE
var tag= child.tagName.toLowerCase();
if (tag!=='script' && tag!=='style' && tag!=='textarea')
replaceInTextNodes(child, needle, replacement);
}
else if (child.nodeType===3)
child.data= child.data.replace(needle, replacement);
}
}
replaceInTextNodes(document.body, /'/g, '\u2665');
来源:https://stackoverflow.com/questions/3899343/javascript-for-replacing-text-in-the-body-tag-of-pages-loaded-into-an-open-sourc