Javascript to replace text in Gmail message (Chrome Extension)
<p>I'm trying to write a Chrome Extension which will replace a string of text in Gmail messages.</p>

<p>If I open a Gmail message and click the print button to see it in print view and run the extension it works well and replaces all instances of the string.</p>

<p>However, if I run the extension in the normal Gmail discussion view it causes the page to refresh and it does not actually replace any of the text.</p>

<p>Here is the code I'm using. Any ideas what I'm doing wrong?</p>

<pre><code>function doIt(){
findAndReplace("Father","Mother");
}

var haystackText = "";
function findAndReplace(needle, replacement) {
 if (haystackText.length == 0) {
      haystackText = document.body.innerHTML;
 }

 var match = new RegExp(needle, "ig");     
 var replaced = "";
 if (replacement.length &gt; 0) {
      replaced = haystackText.replace(match, replacement);         
      document.body.innerHTML = replaced;
 }

}

doIt();
</code></pre>

<p><strong>Update:</strong>
Here is the updated code I'm using after Felix Kling's help. Similar issue to the one above, it works in print preview but not in the regular Gmail view. It does not however reload the page.</p>

<pre><code>function findAndReplace(root, needle, replacement) {
    var children = root.childNodes;
    var pattern = new RegExp(needle, 'ig');
    var node;
    for(var i = 0, l = children.length; i &lt; l; i++) {
        node = children[i];
        if(node.nodeType === 3) { // we have a text node
            node.nodeValue = node.nodeValue.replace(pattern, replacement);
        } else if(node.nodeType === 1) { // Element node
            findAndReplace(node, needle, replacement);
        }
    }
}

function doIt(){
  findAndReplace(document,"Father","Mother");
}

doIt();
</code></pre>
