2

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

document.addEventListener("DOMNodeInserted", checkContents, false);

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

4

1 回答 1

2

将 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

于 2014-10-23T15:05:01.560 回答