Search code examples
javascriptgreasemonkey

Wait inside if command with Greasemonkey


I want to click a button on a page when it appears then wait a few seconds and click another button.

Relevant part of my code is below;

window.onload = function(){
  if(document.getElementsByClassName("btnx").length>0){
      document.getElementsByClassName("btnx")[0].click()
      &(document.getElementsByClassName("btny")[0].click());
  }
}

The problem is when it clicks the btnx it has to wait a few seconds till click btny but it click both almost at same time. Any advise about this will be great.


Solution

  • Here is my version of solution for this

    window.onload = function() {
      let btnx = document.getElementsByClassName("btnx")[0];
      let btny = document.getElementsByClassName("btny")[0];
    
      btny.addEventListener("click", function() {
        console.error("btny clicked");
      });
      btnx.addEventListener("click", function() {
        console.error("btnx clicked");
        setTimeout(function() {
          btny.click();
        }, 1000);
      });
    
      btnx.click();
    };