Javascript 为什么这个突变观察者没有观察到任何突变?
我在Firefox中的GreaseMonkey脚本中执行此操作。我试图通过Ajax检测新添加的子div,我想,这个页面不是我自己的。这是一款聊天/协作应用程序,比如Discord或Slack。我从MDN上的MutationObserver文档复制了这个模式。以下是相关信息:Javascript 为什么这个突变观察者没有观察到任何突变?,javascript,greasemonkey,mutation-observers,Javascript,Greasemonkey,Mutation Observers,我在Firefox中的GreaseMonkey脚本中执行此操作。我试图通过Ajax检测新添加的子div,我想,这个页面不是我自己的。这是一款聊天/协作应用程序,比如Discord或Slack。我从MDN上的MutationObserver文档复制了这个模式。以下是相关信息: function findNewMessages() { console.log("findNewMessages"); // Select the node that will be ob
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);
正在找到targetNode,它是正确的。我输入了一条消息,看着一个新的子元素被添加,但是突变观察者没有触发
根据这里的问题,我找到了另一种我尝试过的形式:
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));
}
}
});
结果相同,无突变。我也试着用另一个答案中的答案,但也有同样的问题。我的javascript和选择器语法已经相当生疏了;我是否遗漏了任何明显的内容?
document.getElementsByClassName(“scrolleriner-2YIMLh”)代码>
返回元素的html集合
observer.observe()
的第一个参数接受特定的元素而不是集合。
因此,您必须使用getElementById
否则,您可以使用for
循环来迭代targetNode
变量。您的控制台应该抱怨传递给MutationObserver的第一个参数。请注意,它不是节点。