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.
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.
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);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With