I'm doing this inside a GreaseMonkey script in Firefox. I'm trying to detect new child divs being added, via Ajax, I assume, this page is not my own. It's a chat/collaboration app like Discord or Slack. I copied this pattern from the MutationObserver docs on MDN. Here's the relevant bits:
function findNewMessages() {
console.log("findNewMessages");
// Select the node that will be observed for mutations
const targetNode = document.getElementsByClassName("scrollerInner-2YIMLh");
if(targetNode) {
console.log("findNewMessages::found scrollerInner");
}
// Options for the observer (which mutations to observe)
const config = { childList: true, subtree: true };
// Callback function to execute when mutations are observed
const callback = function(mutationsList, observer) {
for(const mutation of mutationsList) {
if (mutation.type === 'childList') {
console.log('findNewMessages:: A child node has been added or removed.');
}
else {
console.log("findNewMessages:: mutation : " + JSON.stringify(mutation));
}
}
};
// Create an observer instance linked to the callback function
const observer = new MutationObserver(callback);
// Start observing the target node for configured mutations
observer.observe(targetNode, config);
// Later, you can stop observing
// observer.disconnect();
}
// delay for page to load;
// tried @run-at document-idle in the header but it wasn't working
setTimeout(findNewMessages, 10000);
The targetNode is being found and it is the right one. I typed in a message and watched a new child element being added, but the mutation observer didn't fire.
Based on questions here, I found another form which I tried:
var observer = new MutationObserver(function(mutations) {
for(const mutation of mutationsList) {
if (mutation.type === 'childList') {
console.log('findNewMessages:: A child node has been added or removed.');
}
else {
console.log("findNewMessages:: mutation : " + JSON.stringify(mutation));
}
}
});
Same results, no mutations.
I also tried using the MutationSummary library, found in another answer, but had same problem. My javascript and selector syntax is pretty rusty; am I missing anything obvious?
document.getElementsByClassName("scrollerInner-2YIMLh");
returns html collection of elements
the 1st parameter of observer.observe()
accepts a specific element not a collection.
So you have to use getElementById
.
Otherwise you may use a for
loop to iterate your targetNode
variable.