0

I am building a Chrome extension and want to inject DOM elements or modify some.

For that, I try with my content.js to wait for the DOM to load elements and then use it. However, the DOM element I'm targetting seems to be build after an Async/Await call.

How to access DOM element once Async/Await calls are finished ?

From my content.js :

window.document.onreadystatechange = function () {
  console.log(window.document.readyState); /* "complete" */
  if (window.document.readyState === "complete") {
    console.log(window.document.getElementById('chips')); /* null */
  }
}

The URL I'm targetting is a YouTube live : https://www.youtube.com/watch?v=gxG3pdKvlIs&ab_channel=FRANCE24 (for instance). Running in the DevConsole : window.document.getElementById('chips') correctly log the element.

GuillaumeRZ
  • 2,656
  • 4
  • 19
  • 35
  • 4
    Use a [MutationObserver](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver) to listen for changes to the parent element, then act accordingly when the new content has been added to the DOM. – Rory McCrossan Apr 18 '23 at 14:56
  • 1
    See also [How to detect page navigation on YouTube and modify its appearance seamlessly?](https://stackoverflow.com/a/34100952) – wOxxOm Apr 18 '23 at 15:04

1 Answers1

2

You can use the MutationObserver API to detect when the element is added to the DOM and then modify it.

Here's an example of how you can use MutationObserver to detect when an element with ID chips is added to the DOM:

// Create a new MutationObserver
const observer = new MutationObserver((mutations) => {
  mutations.forEach((mutation) => {
    // Check if the element with ID 'chips' has been added to the DOM
    if (mutation.addedNodes && mutation.addedNodes.length > 0) {
      const chipsElement = document.getElementById('chips');
      if (chipsElement) {
        // Modify the element here
        console.log(chipsElement);
        // Disconnect the observer once the element has been found
        observer.disconnect();
      }
    }
  });
});

// Start observing the document for changes
observer.observe(document, { childList: true, subtree: true });

This code creates a new MutationObserver and starts observing the document for changes. When a change is detected, it checks if the element with ID chips has been added to the DOM. If it has, it modifies the element and disconnects the observer.

You can put this code in your content.js file to wait for the element to be added to the DOM and then modify it.

Patrick
  • 13,872
  • 5
  • 35
  • 53