我正在编写一个简单的用户脚本,如果 Facebook 帖子包含特定的单词列表,它将自动隐藏该帖子。核心功能有效,但我的MutationObserver
似乎没有读过className
of mutation.addedNodes
适当地。我循环遍历mutation.addedNodes
并检查这些元素是否具有该类userContentWrapper
,但该测试的结果始终为 false — 即使该元素确实具有该类。
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);
};
我只能假设观察者在所有属性完全形成之前正在分析添加的节点。如何让观察者等待处理节点直到它完全完成?还是我没理解问题?
提前致谢...
一些添加的节点是容器,因此您应该检查它们的内部:
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 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.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)