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

如何在Google Sheets脚本运行时显示加载提示并阻止用户编辑?

Google Sheets脚本运行时显示加载提示并阻止编辑的解决方案

问题分析

你之前的代码无效的核心原因:

  • HtmlService未设置实际的HTML内容,导致对话框为空
  • 未关联脚本运行状态,无法在脚本结束后自动关闭对话框

实现方案

通过**模态对话框(Modal Dialog)**实现需求:模态框会自动阻止用户编辑当前标签页,同时显示加载提示,脚本运行完成后自动关闭对话框。

完整代码

function runScriptWithLoading() {
  // 初始化UI并创建加载提示的HTML内容
  const ui = SpreadsheetApp.getUi();
  const loadingHtml = HtmlService.createHtmlOutput(`
    <div style="text-align: center; padding: 30px 20px;">
      <p>脚本运行中,请不要关闭页面...</p>
      <div style="border: 3px solid #f0f0f0; border-top-color: #2196F3; border-radius: 50%; width: 45px; height: 45px; animation: spin 1.2s linear infinite; margin: 25px auto;"></div>
      <style>
        @keyframes spin {
          0% { transform: rotate(0deg); }
          100% { transform: rotate(360deg); }
        }
      </style>
    </div>
  `).setWidth(280).setHeight(180);

  // 显示模态对话框
  const dialog = ui.showModalDialog(loadingHtml, '处理中');

  try {
    // --------------- 替换为你的核心业务逻辑 ---------------
    // 示例:模拟耗时操作(实际使用时删除此行,替换为你的代码)
    Utilities.sleep(4000);
    // 示例操作:向A1单元格写入运行结果
    // SpreadsheetApp.getActiveSheet().getRange('A1').setValue('脚本运行完成');
    // ---------------------------------------------------
  } catch (error) {
    // 错误处理:弹出错误提示
    ui.alert('脚本运行失败:' + error.message);
  } finally {
    // 无论成功或失败,都关闭对话框
    dialog.close();
  }
}

使用步骤

  1. 打开你的Google Sheets,点击「扩展程序」→「Apps脚本」
  2. 替换原有的showDialog函数为上述代码
  3. 将你的业务逻辑替换到代码中// 替换为你的核心业务逻辑的位置
  4. 保存脚本,回到表格,重新关联按钮到runScriptWithLoading函数

效果说明

  • 点击按钮后,立即弹出带加载动画的模态对话框,阻止用户编辑当前标签页
  • 脚本运行期间,对话框持续显示状态提示
  • 脚本运行完成(或出错)后,对话框自动关闭,无需用户额外操作

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 11:49:56