1

I'm creating a fairly simple chrome extension. All it needs to do is remove two dom element whenever I visit a specific website.

The problem is that my script runs when $(document).ready and checks if the two elements I'm looking for exist. The two elements don't exist and then my script does not perform it's required task. After the script runs is when the website actually inserts the elements to the html. So my script essentially ran too early.

It doesn't seem like document.ready is actually waiting for all elements to be present. Is there a solution to this?

zms6445
  • 317
  • 6
  • 22

2 Answers2

3

The best approach (imo) is to use a MutationObserver to "observe" the DOM (e.g. the body or better yet, the direct parent of the two elements you want to remove - if you know it beforehand) until those elements are inserted. As soon as you detect each element, you can remove it (and when both have been detected (and removed) you can cancel ("disconnect") the observer to save on resources).

E.g.:

var elem1removed = false;
var elem2removed = false;
var elemParent = document.body; /* or whatever */

var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
        if (mutation.addedNodes && (mutation.addedNodes.length > 0)) {
            var node1 = mutation.target.querySelector(<selectorForElem1>);
            if (node1) {
                node1.parentNode.removeChild(node1);
                elem1removed = true;
            }

            var node2 = mutation.target.querySelector(<selectorForElem2>);
            if (node2) {
                node2.parentNode.removeChild(node2);
                elem2removed = true;
            }

            if (elem1removed && elem2removed) {
                observer.disconnect();
            }
        }
    });
});

observer.observe(elemParent, {
    childList: true,
    subtree: true
});

For a fairly complex example of manipulating dynamically added elements (and how to incorporate the technique into a Chrome Extension), see this other answer.

Community
  • 1
  • 1
gkalpak
  • 47,844
  • 8
  • 105
  • 118
0

If you just want a quick solution without dealing with observers, just use setTimeout so your code runs later. Even safer use setInerval until you find the dom and hide/delete them.

Zig Mandel
  • 19,571
  • 5
  • 26
  • 36