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

Google Sheets脚本ESC键捕获问题:msgBox按ESC报错如何处理

Google Apps Script中捕获ESC键的处理方案

首先明确:原生Browser.msgBox无法直接捕获ESC键,按ESC会直接触发脚本中断错误(即你遇到的"Error resuming script execution"),这是Google Apps Script的内置行为,没有提供钩子拦截该操作。不过可以通过两种替代方案实现类似需求:

1. 使用自定义对话框(HtmlService)—— 推荐方案

这是最灵活的实现方式,通过HTML构建自定义弹窗,可完全控制键盘事件(包括ESC键),还能自定义样式和交互逻辑:

function showCustomDialog() {
  const html = HtmlService.createHtmlOutput(`
    <style>
      .dialog-content { padding: 20px; text-align: center; }
      .dialog-buttons { margin-top: 20px; }
      button { padding: 8px 16px; margin: 0 5px; }
    </style>
    <div class="dialog-content">
      <h3>aaa</h3>
      <p>bbb</p>
      <div class="dialog-buttons">
        <button onclick="google.script.run.withSuccessHandler(closeDialog).handleResponse('OK')">确定</button>
        <button onclick="google.script.run.withSuccessHandler(closeDialog).handleResponse('CANCEL')">取消</button>
      </div>
    </div>
    <script>
      // 监听ESC键事件
      document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
          google.script.run.withSuccessHandler(closeDialog).handleResponse('ESC');
        }
      });
      function closeDialog() {
        google.script.host.close();
      }
    </script>
  `).setWidth(300).setHeight(200);
  
  SpreadsheetApp.getUi().showModalDialog(html, '自定义弹窗');
}

// 接收弹窗返回值并处理的函数
function handleResponse(response) {
  console.log('用户操作:', response);
  // 自定义逻辑处理
  if (response === 'ESC') {
    SpreadsheetApp.getUi().alert('你按下了ESC键');
  } else if (response === 'OK') {
    // 处理确认操作
  }
}

方案说明

  • 通过keydown事件直接捕获ESC键,将自定义返回值(如'ESC')传给后端脚本
  • 完全避免原生msgBox的中断错误,支持自定义弹窗样式、按钮文字等
  • 可灵活扩展交互逻辑,比如添加输入框、复选框等元素

2. 捕获脚本中断错误——临时兼容方案

如果必须使用Browser.msgBox,可以通过try-catch捕获ESC触发的中断错误,间接判断用户按下了ESC键:

function Test1() {
  try {
    var LOCresponse = Browser.msgBox("aaa", "bbb", Browser.Buttons.OK_CANCEL);
    console.log('用户选择:', LOCresponse);
    // 处理OK/CANCEL的逻辑
  } catch (e) {
    // 匹配ESC触发的中断错误信息
    if (e.message.includes('Error resuming script execution')) {
      console.log('用户按下了ESC键');
      // 执行ESC对应的自定义操作
      Browser.msgBox('你按下了ESC键');
    }
  }
}

方案说明

  • 仅能捕获错误并判断ESC操作,无法像自定义对话框那样返回标准化状态值
  • 用户体验较差,因为弹窗会直接消失,错误捕获属于事后处理

总结

优先选择自定义对话框方案,它能完全控制交互流程,支持ESC键的自定义处理并返回状态值;临时兼容场景才考虑try-catch错误捕获方式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 19:42:27