Search code examples
javascriptdomgoogle-chrome-extension

How to access DOM element after async / defer JavaScript run on the ActiveTab?


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.


Solution

  • 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.