开发者

JavaScript for replacing text in the body tag of pages loaded into an open source browser for Android

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 wi开发者_运维问答th 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!


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');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜