【问题标题】:How to stop a new node being added to DOM using Chrome/Firefox extension?如何停止使用 Chrome/Firefox 扩展将新节点添加到 DOM?
【发布时间】:2014-12-19 01:34:48
【问题描述】:

我正在编写一个扩展程序来检测某些脚本的一些恶意行为。这些脚本在页面加载后将一些节点添加到 DOM 中。我可以使用

获取这些节点
document.addEventListener("DOMNodeInserted", checkContents, false);

但是我怎样才能阻止它们被加载呢?这可以在 Chrome 或 Firefox 中完成吗?

【问题讨论】:

    标签: javascript google-chrome-extension firefox-addon dom-events mutation-observers


    【解决方案1】:

    将 MutationObserver 与 childList 和子树一起使用。

    var grid = iframe.contentDocument.getElementById('newtab-grid');
    var mobs = new iframe.contentWindow.MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            console.log(mutation.type, mutation);
            if (mutation.addedNodes && mutation.addedNodes.length > 0) {
                var link = mutation.target.querySelector('.newtab-link');
                if (link) {
                    link.setAttribute('target', '_parent');
                    console.log('set target on this el')
                } else {
                    console.log('this ell has no link BUT it was an added el')
                }
            }
        });
    });
    mobs.observe(grid, {
        childList: !0,
        subtree: !0
    });
    

    现在它会告诉你它何时添加节点,它会给你在mutation.addedNodes 中添加的内容。您可以遍历它并删除添加的内容。我不确定你是否可以阻止它添加,但你肯定可以在添加后将其删除。

    https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver?redirectlocale=en-US&redirectslug=DOM%2FMutationObserver#MutationObserverInit

    【讨论】:

      猜你喜欢
      • 2020-05-13
      • 2020-08-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多