I'm working on a Chrome extension that replaces specified strings or RegEx's in the text of a web page.
It works well overall, but with two issues that I'd like to solve:
(1) The original, unchanged webpage text is displayed before the text replacement occurs.
(2) The text replacement doesn't affect Facebook posts that are dynamically loaded after you scroll to the bottom of the page.
Here's the code, adapted from https://stackoverflow.com/a/6012345#6012345 with minor changes.
// manifest.json
{
"manifest_version": 2,
"name": "Replace Text",
"version": "1.0",
"content_scripts": [ {
"js": [ "jquery.min.js", "replace.js" ],
"matches": [ "<all_urls>" ],
"run_at": "document_end"
} ]
}
// replace.js
jQuery.fn.textWalk = function( fn ) {
this.contents().each( jwalk );
function jwalk() {
var nn = this.nodeName.toLowerCase();
if( nn === '#text') {
fn.call( this );
} else if( this.nodeType === 1 && this.childNodes && this.childNodes[0] && nn !== 'script' && nn !== 'textarea' ) {
$(this).contents().each( jwalk );
}
}
return this;
};
$('body').textWalk(function() {
this.data = this.data.replace('This Text', 'That Text');
this.data = this.data.replace(/[Rr]eplace\s[Ss]ome\s[Tt]ext/g, 'with other text');
});
I found some partial answers online, but couldn’t get them to work right.
For example, one proposed solution was to change "run_at": "document_end"
to "run_at": "document_start"
. This runs content scripts before the DOM is constructed, so in theory it should do the text replacement before anything is displayed. But in my case it caused the extension to stop replacing text altogether.