Content-script: How to wait for React DOM to load?

React app (and Next.js in particular) loads page DOM after `DOMContentLoaded’ event is fired. If content script needs to interact with React app DOM, it needs to wait for them to appear. The following code triggers too early.

document.addEventListener('DOMContentLoaded', function(event) {
  console.log('DOMContentLoaded before class:', document.getElementById('root').textContent);
});

So how to wait for React DOM to load?

To ensure that your content script interacts with the React app DOM after it has fully loaded, you can use the document.readyState property. It allows you to check the current state of the document loading process and can have the following values:

  • "loading" : The document is still loading.
  • "interactive" : The document has finished loading and the DOMContentLoaded event has been fired.
  • "complete" : The document and all its resources have finished loading.

To detect changes to readyState property as the document continues to load, you’ll need to attach an event listener directly to the document:

document.addEventListener('readystatechange', function() {
  if (document.readyState === 'complete') {
    // good luck!
    console.log('React app DOM is fully loaded.');
  }
});