【问题标题】:getting the className of added DOM node (mutationObserver)获取添加的 DOM 节点的类名(mutationObserver)
【发布时间】:2016-10-25 02:18:03
【问题描述】:

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

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);
};

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

提前谢谢...

【问题讨论】:

    标签: javascript dom mutation-observers


    【解决方案1】:

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

    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 键)分析器/时间线面板中进行测试。

    【讨论】:

    • 不会在观察参数中添加childListsubtree 自动深入挖掘吗?
    • 它不会扩展添加的内容。例如,someNode.appendChild(anotherNodeWith1000children) 不会被扩展,因为它只是一个操作。
    • 呵呵,我以为childList 就是这样工作的,然后subtree 会自动搜索所有后代。那么subtree到底在做什么呢?
    • 正如文档所说:subtree 报告后代的突变。一种突变可能包括通过insertAdjacentHTML 或其他方式添加或删除许多节点。而childList 让观察者看到这个活动。没有它,在这些情况下将不会执行回调。
    • 这里多了一个括号
    猜你喜欢
    • 2015-10-18
    • 2019-10-29
    • 2014-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多