获取添加的DOM节点的className(mutationObserver) [英] getting the className of added DOM node (mutationObserver)
问题描述
我正在编写一个简单的用户脚本,如果其中包含某些单词列表,它将自动隐藏Facebook帖子。核心功能有效,但是我的 MutationObserver
似乎没有读取突变的
正确。我遍历 className
.addedNodes mutation.addedNodes
并检查其中任何一个元素是否具有类 userContentWrapper
,但是该测试的结果始终为false -即使元素确实具有类。
I'm writing a simple userscript that will auto-hide a Facebook post if it contains a certain list of words. The core functionality works, but my MutationObserver
doesn't seem to read the className
of mutation.addedNodes
properly. I loop through mutation.addedNodes
and check if any of those elements have the class userContentWrapper
, but the result of that test is always false -- even if the element does have the class.
var startObserver = function() {
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
var added = mutation.addedNodes;
for (var i = 0; i < added.length; i++) {
if (/\buserContentWrapper\b/.test(added[i].className)) {
processFilter(added[i]);
}
}
});
});
var obj = {childList: true, subtree: true, attributes: true};
observer.observe(document.documentElement, obj);
};
我只能假设观察者正在分析添加的节点,直到它完全具有地点。如何让观察者等待处理节点,直到节点完全完成?还是我不理解这个问题?
I can only assume that the observer is analyzing the added node before it's fully formed with all the attributes in place. How can I make the observer wait to process the node until it's fully complete? Or am I not understanding the problem?
预先感谢...
推荐答案
一些添加的节点是容器,因此您应该检查它们的内部:
Some of the added nodes are containers so you should check their insides:
const observer = new MutationObserver(onMutation);
observer.observe(document, {
childList: true,
subtree: true,
});
function onMutation(mutations) {
const found = [];
for (const { addedNodes } of mutations) {
for (const node of addedNodes) {
if (!node.tagName) continue; // not an element
if (node.classList.contains('userContentWrapper')) {
found.push(node);
} else if (node.firstElementChild) {
found.push(...node.getElementsByClassName('userContentWrapper'));
}
}
}
found.forEach(processFilter);
}
MutationObserver回调是作为阻止DOM和JS引擎的微任务执行的,因此尝试使其速度更快,尤其是如果它运行在生成大量DOM突变的复杂网站(例如facebook)上时。可以在devtools( F12 键)事件探查器/时间轴面板中进行测试。
MutationObserver callback is executed as a microtask that blocks DOM and JS engine so try to make it fast, especially if it runs on a complex site such as facebook that generates lots of DOM mutations. This can be tested in devtools (F12 key) profiler/timeline panels.
这篇关于获取添加的DOM节点的className(mutationObserver)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!