Monitor elements in real-time as they are inserted into the DOM using a Chrome Extension

In the process of developing a Chrome extension, I am tackling the task of removing or hiding specific elements based on their id/class. While accomplishing this after the DOM is loaded poses no issue, it does result in a noticeable "blink" on the page during the element removal process. To address this, my objective is to handle the removal while the elements are being added to the DOM.

My aim is to delete designated elements as they are introduced into the DOM structure.

I have been referencing this resource, but my current implementation only allows me to access the HTML node without being able to target the other elements.

The contentScript.js script I am working with looks like this:


const mo = new MutationObserver(onMutation);
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,
    });
}

Within my manifest file, I have included:

  "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"]
    }
  ],

Despite these efforts, my console output only displays the html node and not the additional elements being added. Am I taking the wrong approach here?

Answer №1

For those struggling with a similar issue, here is how I resolved it: Following the advice of @wOxxOm, I verified that the code was correct. The problem seemed to be related to the tab itself - simply closing and reopening it worked for me. It's unclear why this fixed the issue, but attempting to refresh the tab didn't work as expected. Closing the specific tab the extension was monitoring and then reopening it did the trick.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting: The issue of receiving a 403 error when trying to access

I'm currently using Codeigniter 3 and have encountered an issue with a script. When the code is in my HTML file, everything works perfectly fine. However, if I move the code to an external file, I receive a 403 error. The location of my JavaScript fi ...

Leveraging ES6 import declarations within Firebase functions

I've been experimenting with using ES6 in Firebase functions by trying to import modules like "import App from './src/App.js'. However, after adding type:"module" to my package.json, I encountered a strange error with Firebase ...

Exploring Node.js and JSON: Retrieving specific object attributes

Utilizing ExpressJS, NodeJS, and Bookshelf.js In an attempt to display a user's list of friends, encountering the error "Unhandled rejection TypeError: Cannot read property 'friends' of undefined" when trying to access a property of the obj ...

An unrecoverable error has occurred in the SetForm function: PHPMailer::SetForm() method is not defined

While working on form validation in jQuery with a WAMP server, I encountered two errors: Fatal error: Uncaught Error: Call to undefined method PHPMailer:: SetForm() and Error: Call to undefined method PHPMailer::SetForm(). I have already added PHPMailerAu ...

"Step-by-step guide on uploading multiple images to a Node server and storing them in

Hey everyone! I'm currently working on a project using React and MongoDB. Users are required to register and login before accessing the app. Once logged in, they can input their name, number, and images through a form. However, I've encountered a ...

Encapsulating data with JSON.stringify

I'm currently working on creating an object that has the following structure: let outputOut = { "_id": id[i], "regNum": code[i], "sd": sd[i], "pd": ptOut, "p": p[i], ...} //output fs.writeFile('./output/file.json', JSON ...

What is the best method to generate a distinct identifier for individual input fields using either JavaScript or jQuery?

I have attempted to copy the table n number of times using a for loop. Unfortunately, the for loop seems to only work on the first iteration. I am aware that this is due to not having unique IDs assigned to each table. As a beginner, I am unsure how to cre ...

Change the flyout menu to activate once clicked instead of when the mouse hovers over

Want to add a cool flyout menu action that triggers on click instead of mouseover? The current code triggers the flyouts on mouseover, but I need them to open only when clicked. Specifically, I'd like to change the functionality so that you click on a ...

Utilizing localstorage data in angular 2: A comprehensive guide

Is there a way to utilize data stored in localstorage for another component? This is what the localstorage service looks like: localStorage.setItem('currentUser', JSON.stringify({ username: username, token: success, res: res.data })); I am inte ...

Turning off strict mode in the bundling process of React with webpack can be achieved by following

I'm facing an issue with my application. It works perfectly in all browsers except for IE, where it throws the following error: 0x800a0416 - JavaScript runtime error: Multiple definitions of a property not allowed in strict mode In my webpack.config ...

Kik Card - Using Synchronous XMLHttpRequest within the Kik.js Script

Getting ready to create a mobile web app powered by Kik! First step, insert the Kik.js script at the bottom of your HTML page... <!-- add this script to your webpage --> <script src="http://cdn.kik.com/kik/2.3.6/kik.js"></script> Excel ...

Can you tell me the name of the Javascript "protocol" or "custom" being referred to here?

From what I can gather, the requests array seems to consist of functions with unique formatting and syntax. However, I'm struggling to find relevant search terms to help me better understand it: var requests = { rewardPoints: function(cb) { io ...

Using Framework7 and AngularJS to efficiently load pages

When creating a phone application using phonegap, AngularJS, and Framework7, I encountered an issue with the page swapping functionality of Framework7. The problem arises because Framework7 injects new HTML pages into the DOM dynamically when a user click ...

Customizing the layout of specific pages in NextJSIncorporating

In my Next.js project, I'm trying to set up a header and footer on every page except for the Login page. I initially created a layout.tsx file in the app directory to apply the layout to all pages, which worked fine. However, when I placed another lay ...

The onPlayerReady function in the YouTube API seems to be experiencing a delay and

After following a tutorial on integrating the YouTube API into my website, I encountered difficulties trying to play a YouTube video in fullscreen mode when a button is pressed. Despite following the provided code closely, I am unable to get it to work as ...

PHP not receiving POST information from $.ajax call

My JavaScript triggers a POST method when the datepicker loses focus, calling the script rent-fetch-pick-up-point.php. However, the PHP script gets stuck at the if-statement because it's not receiving the POST data. The datepicker is associated with a ...

HTML code displaying a fixed message at the top of the webpage

I'm working on a web page that has a lot of content. I need to have a message always visible at the bottom of the browser window, even when scrolling. Can anyone help me achieve this using simple CSS, HTML, jQuery, or PHP? Thanks! ...

Is it possible to redirect any web traffic using an authentication script?

Scenario: I'm currently working on a social networking project and I'm looking for a way to validate every redirect or refresh by directing the user through another script before reaching their final destination. I've considered using a &apo ...

Error: Trying to call an undefined function

Having trouble with an error on this line: $("#register-form").validate. Can anyone offer assistance? Furthermore, if I write this script, how should I incorporate it into the form? Will it function without being called? <script type="text/javascript ...

When the VueJS element is rendered on Chrome addon, it suddenly vanishes

I have been using a developer mode addon successfully in Chrome for quite some time. Now, I want to add a button to my Vue-powered page. Here's the code snippet: let isletCtl = document.createElement('div') isletCtl.id ...