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

Google Apps Script:google.script.run共享账户超时暂停问题

问题原因与解决方案

核心问题分析

你的问题出在非所有者用户通过google.script.run调用服务端函数时,函数内使用SpreadsheetApp.getUi().alert()导致脚本挂起超时。

原因如下:

  • 菜单触发的函数是在用户当前的UI交互上下文里直接执行的,属于同步前端触发操作,SpreadsheetApp.getUi()能正常唤起弹窗。
  • 而google.script.run是异步远程服务端调用,服务端函数尝试调用Ui.alert()时,非所有者用户的权限和上下文无法支持服务端直接触发用户界面弹窗,导致脚本卡在这一步直至超时。

解决方案

不要在google.script.run调用的服务端函数中使用服务端UI弹窗,改为将提示内容返回给前端,在HTML侧边栏里用JavaScript实现弹窗。

修改后的Code.gs代码

/**
 * @OnlyCurrentDoc
 */

function onOpen(e) {
  let ui = SpreadsheetApp.getUi();

  ui.createMenu("Menu")
  .addItem("Call Dialog from Menu", "test") // 修正原代码函数名笔误(原写teste,实际函数是test)
  .addItem('Call Sidebar', "showSidebarForm")
  .addToUi();
}

function test() {
  Logger.log("Called")
  // 移除服务端alert,改为返回提示内容给前端
  Logger.log("Ended")
  return "message";
}

function showSidebarForm() {
  var userForm = HtmlService.createTemplateFromFile("test-form").evaluate().setTitle("Test Sidebar");
  SpreadsheetApp.getUi().showSidebar(userForm)
}

修改后的HTML侧边栏代码

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <button id="test-button">Call Dialog from Sidebar</button>
  </body>
  <script>
    let button = document.querySelector("#test-button");

    button.addEventListener("click", () => {
      google.script.run
        .withSuccessHandler((message) => {
          // 在前端显示弹窗
          alert("title: " + message);
        })
        .test();
    })
  </script>
</html>

额外说明

  • 部署设置的「执行身份」和「访问权限」配置本身没问题,问题出在服务端函数的UI交互逻辑不兼容google.script.run的调用方式。
  • 所有需要和用户交互的弹窗、提示,都应该放在前端HTML里实现,服务端只负责数据处理和返回结果。

内容的提问来源于stack exchange,提问作者Jonas Felix de Souza

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 22:08:20