Search code examples
javascripttextreplacegoogle-chrome-extensioncontent-script

Replace text but keep links in google chrome extension content scripts


I am trying to replace words on google chrome but have run into an issue. I am able to successfully replace specific words but it kills associated html links.

How can I keep links live and still replace text?

This is the code in my chrome extension content scripts:

wordDict = {"the":"piano","and":"Hello", "a":"huh?"};

for (word in wordDict) {
    document.body.innerHTML = document.body.innerHTML.replace(
        new RegExp('\\b' + word + '\\b',"gi"), wordDict[word]
    );
};

Solution

  • Okay! 2 Weeks later I finally resolved the issue. What was being ignored were the childnodes inside the DOM. The code I am using below effectively addresses the childnodes and maintains the original appearance of the script!

    function replaceText(jsonArr) {
    $("body *").textFinder(function() {
        for (var key in jsonArr) {
            var matcher = new RegExp('\\b' + key + '\\b', "gi");
            this.data = this.data.replace(matcher, jsonArr[key]);
        }
    });
    }
    
    // jQuery plugin to find and replace text
    jQuery.fn.textFinder = function( fn ) {
    this.contents().each( scan );
    // callback function to scan through the child nodes recursively
    function scan() {
        var node = this.nodeName.toLowerCase();
        if( node === '#text' ) {
            fn.call( this );
        } else if( this.nodeType === 1 && this.childNodes && this.childNodes[0] && node !== 'script' && node !== 'textarea' ) {
            $(this).contents().each( scan );
        }
    }
    return this;
    };