2
\$\begingroup\$

Here is the problem: some script is injecting some HTML5 elements (actually a button with the #thebutton ID) to the current DOM.

But this is a third party script and I have no control of when this will be injected to the page. I need to click automatically on this button when the button is injected to the DOM. Here is my solution so far.

It's actually working but I'm not sure on how fine this code is. My first guess is that I may use the clearTimeout() method. Is there anything else I must do?

<script type="text/javascript">
    function waitForElementToDisplay(selector, time) {
        if (document.querySelector(selector) !== null) {
            document.getElementById("thebutton").click();
            return;
        } else {
            setTimeout(function () {
                waitForElementToDisplay(selector, time);
            }, time);
        }
    }
    // onload
    (function () {
        waitForElementToDisplay("#thebutton", 500);
    })();
</script>

Here is a simulated jsFiddle of the whole process: https://jsfiddle.net/qxpcj3wm/

\$\endgroup\$
7
  • \$\begingroup\$ Could you provide us a scenario (actual html, script) where you would use this? \$\endgroup\$ – dfhwze Jul 5 '19 at 14:40
  • \$\begingroup\$ Actually it's a video player which is loaded. It has no API to force it loading and the end-user must click to a button to fully load it. I want to save this useless click for all end-users. \$\endgroup\$ – F3L1X79 Jul 5 '19 at 14:42
  • \$\begingroup\$ @dfhwze Do you require a jsfiddle of some sort? \$\endgroup\$ – F3L1X79 Jul 5 '19 at 14:44
  • \$\begingroup\$ Sure, that would do it :) Also check out mutation observers \$\endgroup\$ – dfhwze Jul 5 '19 at 14:45
  • 1
    \$\begingroup\$ jsfiddle.net/qxpcj3wm \$\endgroup\$ – F3L1X79 Jul 5 '19 at 14:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.