views:

52

answers:

1

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!

A: 

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');
bobince
Thanks a lot! I could solve that replacement issue with your help. Currently I'm executing the JavaScript at event.equals(EventConstants.EVT_WEB_ON_PAGE_FINISHED - Therefore in case of large pages, it will take a lot of time to replacements take place since it has to wait until the full page get loaded. Do I have any better place to execute this script such that the replacements take place as soon as the page is visible (before the whole page get loaded) ? Appreciate your help!
Dhanika
You'd have to keep checking on a interval timer, I guess. It would be a real pain to try to keep track of which elements on the page had been completely loaded to avoid re-replacing over the same text nodes twice. Luckily in this case a re-replace is harmless so you can get away with running the replacement several times.
bobince
Dhanika