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

I am writing JavaScript for the open source browser available for Android, for replacing text in tag tag loaded pages in a browser with some text.

This needs to be worked out, because after the page is loaded into the browser, this JavaScript is executed, and replacements are performed, and, finally, the page with the replaced text is visible in the browser.

This is the replacement 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 does not seem to work. Can someone help me fix this code or any suggestions to do this by replacing the body text task in some other way?

Thanks!

0
source share
1 answer

Sorry, you are not getting DOM Level 3 XPath in the Android browser .

Although you can use the JavaScript XPath implementation ( for example ), it will be a slow and cumbersome solution compared to writing specific DOM bypass 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
source

Source: https://habr.com/ru/post/888175/


All Articles