Skip to content Skip to sidebar Skip to footer

Replace Many Text Terms, Using Tampermonkey, Without Affecting Urls And Not Looking For Classes Or Ids

I'm writing a Google Chrome extension for a popular e-commerce SAAS which will replace English text strings to Spanish inside its admin panel. I've come with a solution which repla

Solution 1:

To avoid trashing URL's, id's, event handler's, etc.; you need to act only on the TEXT_NODEs of a web page. Never use innerHTML.

An efficient way to act on text nodes is to use a Tree Walker.

For the 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 nodesif (node.nodeValue.trim() )
                returnNodeFilter.FILTER_ACCEPT;

            returnNodeFilter.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;
}

Post a Comment for "Replace Many Text Terms, Using Tampermonkey, Without Affecting Urls And Not Looking For Classes Or Ids"