You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript自动点击window.prompt()的确认按钮?

如何自动确认JavaScript的window.prompt()弹窗?

嘿,我来帮你搞定这个问题!首先得说清楚:原生的window.prompt()是浏览器提供的系统级模态弹窗,它会直接阻塞JavaScript的执行线程,而且出于安全限制,浏览器并没有提供API让我们直接模拟点击它的“确认”按钮。

不过别担心,我们可以通过重写window.prompt方法来绕过这个限制——相当于自己模拟一个prompt的行为,直接返回我们想要的预设值,这样就达到了“自动确认”的效果。

具体实现步骤

  • 在调用prompt之前,重写window.prompt函数,让它直接返回你想要的文本(比如示例里的"example text"或者自定义内容)。
  • 这样当你的代码调用prompt时,不会弹出真实的弹窗,而是直接拿到预设的返回值,就像用户点击了确认按钮一样。

修改后的完整示例代码

<!DOCTYPE html>
<html>
<body>
<h2>PS Prompt test</h2>
<button onclick="Function()" id="test">send value</button>
<p id="demo"></p>
<script>
// 先重写window.prompt方法,自动返回预设值
window.prompt = function(message, defaultValue) {
  // 这里直接返回默认值,模拟用户点击确认
  return defaultValue;
};

function Function() {
  var txt;
  var text = prompt("Please enter text:", "example text");
  if (text == null || text == "") {
    txt = "User cancelled the prompt.";
  } else {
    txt = "You entered: " + text;
  }
  // 把结果显示到页面上
  document.getElementById("demo").innerHTML = txt;
}
</script>
</body>
</html>

额外说明

如果是在自动化测试场景(比如需要控制真实浏览器弹窗),你可以用像Puppeteer这样的自动化工具,它能模拟用户操作浏览器的行为,包括点击prompt的确认按钮。但如果是在普通前端页面里,重写prompt是最直接可行的方案。

内容的提问来源于stack exchange,提问作者Anton Savichev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:12:37