gpt4 book ai didi

javascript - 获取添加的 DOM 节点的类名 (mutationObserver)

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:42:22 24 4
gpt4 key购买 nike

我正在编写一个简单的用户脚本,如果它包含特定的单词列表,它将自动隐藏 Facebook 帖子。核心功能有效,但我的 MutationObserver 似乎没有正确读取 mutation.addedNodesclassName。我遍历 mutation.addedNodes 并检查这些元素中是否有任何元素具有 userContentWrapper 类,但该测试的结果始终为 false——即使该元素确实具有类(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);
};

我只能假设观察者正在分析添加的节点,然后才完全形成所有属性。我怎样才能让观察者等待处理节点直到它完全完成?还是我不明白问题所在?

提前致谢...

最佳答案

一些添加的节点是容器,所以你应该检查它们的内部:

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。这可以在开发工具(F12 键)分析器/时间线面板中进行测试。

关于javascript - 获取添加的 DOM 节点的类名 (mutationObserver),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37979897/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com