1

I'm making an extension that will put a button under each video on the home page but I found out very quickly that this wouldn't be possible by just using a selectAll statement. The only thing that a selectAll statement does is it retrieves the first 3 rows of videos on the homepage. I think what's happening is there are videos being loaded after the page has loaded thus the elements don't exist at "document_end"(this being when my chrome extension is injecting the js/css onto the page). I would be looking for something like an event listener but an explanation as to why this is happening would be appreciated as well.

Peter
  • 15
  • 6

1 Answers1

0

You could solve this by using MutationObservers in your content script.

Example from mdn web docs below, you should be able to call and find new elements by using document.querySelectorAll() inside the callback function.

// Keep track of DOM element changes under <html> and run callback with mutationsList and observer once DOM changes
// Select the node that will be observed for mutations
const targetNode = document.getElementById('some-id');

// Options for the observer (which mutations to observe)
const config = { attributes: true, childList: true, subtree: true };

// Callback function to execute when mutations are observed
const callback = function(mutationList, observer) {
    // Use traditional 'for loops' for IE 11
    for(const mutation of mutationList) {
        if (mutation.type === 'childList') {
            console.log('A child node has been added or removed.');
        }
        else if (mutation.type === 'attributes') {
            console.log('The ' + mutation.attributeName + ' attribute was modified.');
        }
    }
};

// Create an observer instance linked to the callback function
const observer = new MutationObserver(callback);

// Start observing the target node for configured mutations
observer.observe(targetNode, config);

// Later, you can stop observing
observer.disconnect();

Nicholas Wong
  • 198
  • 3
  • 9
  • Ok so this worked however when I put in my for loop to go through and inject the HTML into the page it will go into an infinite loop of adding the HTML and then checking if there is a change (which there will be because the content script keeps adding it). – Peter May 26 '22 at 23:44
  • You could check if the button already exists under that video before placing another one, that way it won't activate another loop. – Nicholas Wong May 27 '22 at 00:02
  • I got it! I took out all of the conditions in config except for childList which made it much more efficient, and I added a check to see if it already had the button under it. Thank you – Peter May 27 '22 at 01:07