-1

I am trying to auto-populate some input fields when the page fully loads. However, there are other scripts I can't control which change the page. So if I try to do anything like these options, I get element not found.

window.addEventListener("load", (event) => {
    init();
});

or

if (document.readyState !== "loading") {
  init();
} else {
  document.addEventListener("DOMContentLoaded", function () {
    init();
  });
}

When can I call init() so that all other scripts have been executed (aka I won't get element not found error)? Right now, I am using setTimeOut() which obviously isn't ideal.

References:

How to detect if DOMContentLoaded was fired

document.readyState on DOMContentLoaded?

Student
  • 89
  • 1
  • 8
  • 2
    if it helps, you can inspect each change that happens to the document using a [MutationObserver](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver). – IT goldman May 20 '23 at 20:47
  • 1
    There's no such event unless the site itself fires a custom nonstandard one, which you can try finding in devtools, but that's rare. The universal solution is MutationObserver. – wOxxOm May 21 '23 at 05:12

1 Answers1

0

const observer = new MutationObserver(function (mutationsList) {
  if (document.querySelector("input[data-automation-id]")) {
    init();
    observer.disconnect();
  }
});
observer.observe(document, { childList: true, subtree: true });

Thought of this based on the comment. However, it is still a proxy so this does not guarantee ALL input fields are available.

Student
  • 89
  • 1
  • 8