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?