0

I am creating a Chrome extension that will remove/hide certain elements based on their id/class. I can do this no problem after the DOM is loaded. However, this causes a "blink" on the page when the elements are being removed so I wanted to do it while the elements are being added to the DOM.

For example, I want to delete certain elements as they are being added to the DOM.

I am following https://stackoverflow.com/a/32537455/13181058, but I only get the HTML node, not the rest of the elements.

My contentScript.js:


const mo = new MutationObserver(onMutation);
// in case the content script was injected after the page is partially loaded
onMutation([{ addedNodes: [document.documentElement] }]);
observe();

function onMutation(mutations) {
    let stopped;
    for (const { addedNodes } of mutations) {
        for (const n of addedNodes) {
            if (n.tagName) {
                if (n.tagName == 'DIV'){
                    n.remove();
                }
            }
        }
        if (stopped) observe();
    }
}

function observe() {
    mo.observe(document, {
        subtree: true,
        childList: true,
    });
}

My manifest includes:

  "content_scripts": [
    {
      "matches": ["https://*.somewebsite.com/*"],
      "run_at": "document_start",
      "all_frames": true,
      "js": ["/static/thirdParty/jquery-3.6.3.min.js", "/static/contentScript.js"]
    }
  ],

However, all I get in the console is the html node and not the rest of the elements that are being added.

Is this the wrong approach?

ehtio
  • 179
  • 3
  • 11
  • 1
    The code seems fine. You probably didn't click the reload icon in chrome://extensions page after editing. – wOxxOm Mar 20 '23 at 13:49
  • Unfortunately I did reload the extension. If I remove "run_at": "document_start", "all_frames": true, from the manifest.json, then it will work but it waits until all the DOM elements are added, which products a blink on the elements that are removed. – ehtio Mar 20 '23 at 13:58
  • @wOxxOm I updated the question. Let's say I want to remove all the elements that are divs. It doesn't work. Strangely, it worked a few of the times I refreshed. No idea why.... – ehtio Mar 20 '23 at 14:35

1 Answers1

0

Not sure if this will help anybody, but this is how I sorted it out. Like @wOxxOm said, there is nothing wrong with the code. The issues was that I had to close and reopen the tab again. I am not sure why this helped but I was trying to reload the current tab and the code was not working. However, closing the tab that the extension was listening to and opening it again helped.

ehtio
  • 179
  • 3
  • 11