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

混江龙づ霸主 提交于 2019-12-25 07:59:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!