1
function waitForElm(selector) {
    return new Promise(resolve => {
        if (document.querySelector(selector)) {
            return resolve(document.querySelector(selector));
        }

        const observer = new MutationObserver(mutations => {
            if (document.querySelector(selector)) {
                resolve(document.querySelector(selector));
                observer.disconnect();
            }
        });

        observer.observe(document.body, {
            childList: true,
            subtree: true
        });
    });
}

waitForElm('.some-class').then((elm) => {
    console.log('Element is ready');
    console.log(elm.textContent);
});

How does this answer from the popular question work? It returns an error for me:

Uncaught (in promise) TypeError: Failed to execute 'observe' on 'MutationObserver': parameter 1 is not of type 'Node'.

at content-script.js:14:18
at new Promise (<anonymous>)
at waitForElm (content-script.js:2:12)
at content-script.js:21:1

It probably doesn't find the document.body element.

senops
  • 31
  • 3
  • Looks like the `document.body` does not exist when you invoke the `observer.observe`. Have you tried to put the script at the end of your body tag? – Niro Feb 25 '23 at 09:02
  • I need it when my extension starts. – senops Feb 25 '23 at 09:08
  • Ok if my suggested issue is the actual culprit, then listening to the body onload event would be an other option. But without a reproducable example one can only guess the issue, maybe add one. – Niro Feb 25 '23 at 10:18
  • Use `document` or `document.documentElement` instead of `document.body`. – wOxxOm Feb 25 '23 at 12:05
  • @wOxxOm Thank you very much! I didn't know it was possible. – senops Feb 25 '23 at 13:12

0 Answers0