Search code examples
javascripttampermonkey

closing a browser tab with window.close() only after function finishes runing


I have the following function injected with Tampermonkey (part of a bigger piece of code)

document.addEventListener("keydown", function(e) {
  if ((e.keyCode == 83 || e.keyCode == 32) && e.ctrlKey) {
    e.preventDefault();
    [...document.querySelectorAll('button.btn.btn-primary.pull-end')]
      .filter(x => x.innerText.includes('aaa'))[0]
      .click()
    if (window.location.hash.match(/#*/)) {
      window.close()
    }
  }
}, false);

the problem is the tab closes before the click() function finishes I understand probably I will have to use callback but I can not get it working any help please


Solution

  • I ended up doing it this way by adding a timeout function and it works fine

    document.addEventListener("keydown", function(e) {
      if ((e.keyCode == 83 || e.keyCode == 32) && e.ctrlKey) {
        e.preventDefault();
        [...document.querySelectorAll('button.btn.btn-primary.pull-end')]
          .filter(x => x.innerText.includes('aaa'))[0]
          .click()
        if (window.location.hash.match(/#*/)) {
          setTimeout(() => window.close(), 1000);
        }
      }  
    }, false);