首页 > 解决方案 > 仅在函数完成运行后使用 window.close() 关闭浏览器选项卡

问题描述

我用 Tampermonkey 注入了以下函数(更大的代码的一部分)

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);

问题是在 click() 函数完成之前选项卡关闭我理解可能我将不得不使用回调但我无法让它工作任何帮助请

标签: javascripttampermonkey

解决方案


我最终通过添加超时功能来做到这一点,它工作正常

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);

推荐阅读