Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MutationObservers - Some nodes added are not detected

I have a content script which listens for the insertion of text-nodes on some websites. It's working great, except on Facebook. Some of the text-nodes inserted are not detected by the script.

script.js

var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
        if (mutation.type  === "characterData") {
            console.log(mutation.target);
        } else {
            for (var x = 0; x < mutation.addedNodes.length; x++) {
                var node = mutation.addedNodes[x];
                if (node.nodeType === Node.TEXT_NODE) {
                    console.log(node);
                }
            }
        }
    });
});
observer.observe(document, { childList: true, subtree: true, characterData: true });

If I allow logging of all node types, I can see the parent nodes of these text nodes in my log.

Thanks.

like image 376
Red John Avatar asked Nov 01 '13 16:11

Red John


1 Answers

This is probably the same issue as this question. If a script "builds" elements outside of the DOM and then attaches the root, only the root will be reported as an added node. TreeWalker can be used to traverse the added node's subtree to find the text.

for (const addedNode of mutation.addedNodes) {
    if (addedNode.nodeType === Node.TEXT_NODE) {
        console.log(addedNode);
    } else {
        // If added node is not a Text node, traverse subtree to find Text nodes
        const nodes = document.createTreeWalker(addedNode, NodeFilter.SHOW_TEXT);
        while (nodes.nextNode()) {
            console.log(nodes.currentNode);
        }
    }
}
like image 144
Daniel Ting Avatar answered Oct 20 '22 01:10

Daniel Ting