I'm writing a userscript to replace every occurrence of a word in a page with another word (think the cloud
-> my butt
). It's based on this script https://github.com/panicsteve/cloud-to-butt/blob/master/Source/content_script.js
Normally this is easy. I just need to run it when the page finished loading. However, I'm doing this to the Facebook news feed, and the script only applies to the contents that were load initially. When I scroll down and new contents are loaded, the text in those new contents are not touched by the script.
How can I make it so that when new contents are loaded when I scroll down the page, the script runs again?
In the end I used MutationObserver
:
// select the target node for mutation observation
var target = document.body;
// create an observer instance
var observer = new MutationObserver(function(mutations) { // mutations: an array of MutationRecord objects
mutations.forEach(function(mutation) {
var addedList = mutation.addedNodes;
for (var i = 0; i < addedList.length; ++i) {
// do something with addedList[i]
}
});
});
// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true, subtree: true };
// pass in the target node, as well as the observer options
observer.observe(target, config);