Replace many text terms using Tampermonkey without affecting URLs or looking for classes or identifiers

I am writing the Google Chrome extension for the popular e-commerce SAAS, which will replace English text strings with Spanish in my admin panel.

I came up with a solution that replaces EVERYTHING, so when searching for href it also replaces it, which is undesirable:

var els = document.getElementsByTagName("*"); for(var i = 0, l = els.length; i < l; i++) { var el = els[i]; // ==Menu_left_dropdown== el.innerHTML = el.innerHTML.replace(/View your user account/gi, 'Tu cuenta'); el.innerHTML = el.innerHTML.replace(/Terms of service/gi, 'Términos y condiciones'); el.innerHTML = el.innerHTML.replace(/Privacy policy/gi, 'Privacidad'); el.innerHTML = el.innerHTML.replace(/Log out/gi, 'Salir'); // ==Menu_left= el.innerHTML = el.innerHTML.replace(/Search/gi, 'Buscar'); el.innerHTML = el.innerHTML.replace(/Dashboard/gi, 'Panel'); el.innerHTML = el.innerHTML.replace(/Orders/gi, 'Pedidos'); el.innerHTML = el.innerHTML.replace(/Customers/gi, 'Clientes'); el.innerHTML = el.innerHTML.replace(/Products/gi, 'Productos'); } 

Obtaining elements by class or identifier would not be easy to maintain, as they could change without the platform informing us. I also plan to add more locales, so any suggestion on how to approach a cleaner way of organizing strings would be great.

0
source share
1 answer

To avoid handling URLs, identifiers, event handlers, etc .; you only need to act on the TEXT_NODE webpage. Never use innerHTML .

An effective way to work with text nodes is to use Tree Walker .

For replacement terms, use an array.

Putting it all together, the code looks like this:

 var replaceArry = [ [/View your user account/gi, 'Tu cuenta'], [/Terms of service/gi, 'Términos y condiciones'], [/Privacy policy/gi, 'Privacidad'], // etc. ]; var numTerms = replaceArry.length; var txtWalker = document.createTreeWalker ( document.body, NodeFilter.SHOW_TEXT, { acceptNode: function (node) { //-- Skip whitespace-only nodes if (node.nodeValue.trim() ) return NodeFilter.FILTER_ACCEPT; return NodeFilter.FILTER_SKIP; } }, false ); var txtNode = null; while (txtNode = txtWalker.nextNode () ) { var oldTxt = txtNode.nodeValue; for (var J = 0; J < numTerms; J++) { oldTxt = oldTxt.replace (replaceArry[J][0], replaceArry[J][1]); } txtNode.nodeValue = oldTxt; } 
+4
source

All Articles