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
A viable alternative would be to listen for DOM changes by means of a MutationObserver and change the content of TextNodes (or what ever) on the fly. Technically, this does not happen before anything is being rendered, but it should be close enough for the user not to notice (unless the changes you make are massive).
See, also, my answer to a similar question.
(This still needs twicking, e.g. to handle dynamic node updates.)
content.js:
// Modify the content somehow...
var doFilter = function(textNode) {
textNode.data = textNode.data + "<br />" + textNode.data;
}
// Create a MutationObserver to handle events
// (e.g. filtering TextNode elements)
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.addedNodes) {
[].slice.call(mutation.addedNodes).forEach(function(node) {
if (node.nodeName.toLowerCase() == "#text") {
doFilter(node);
}
});
}
});
});
// Start observing "childList" events in document and its descendants
observer.observe(document, {
childList: true,
subtree: true
});
(The above code it for listening for added nodes. You might want to have an observer listen for characterData
and childList
changes in body and its descendants for "catching" dymanically loaded/changed content.)
manifest.json:
...
"content_scripts": [
{
"matches": [...],
"js": ["content.js"],
"run_at": "document_start",
"all_frames": true
}
],
...
If you decide to go for the MutationObserver approach, there is this JS library that is supposed to make your life easier: mutation-summary
Regarding your question, why executing your script at "document_start" does not have any effect:
This happens, because at that time ("document_start") there is nothing for your script to replace (i.e. it is loaded and run before any other content is added to the DOM).