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

使用google.script.run调用函数失败的排查求助

问题描述
  • 相同代码复制到新的Apps Script项目可正常运行,但在特定共享表格中使用时,HTML模态框的提交按钮触发runThis()后,alert("Hi!")正常执行,但google.script.run.doSomething()无响应,执行历史无相关记录
  • 单独在控制台运行doSomething()可成功弹出提示并打印日志
  • 添加success/failure handler后返回错误:

NetworkError: Connection failure due to HTTP 500

  • 需求:用美观的日历选择器替代SpreadsheetApp.getUi().prompt()获取日期,同时解决当前的函数执行问题

提供的代码

HTML代码(CalendarInput.html)

<html>
<head>
  <title>HTML</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

  <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/themes/smoothness/jquery-ui.css"
    crossorigin="anonymous" referrerpolicy="no-referrer" />
  <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js" crossorigin="anonymous"
    referrerpolicy="no-referrer"></script>
  <script>
    $(function () {
                $("#datepicker").datepicker({
                    beforeShowDay: function (d) {
                        var day = d.getDay();
                        return [day != 0 && day != 2 && day != 3 && day != 4 && day != 5 && day != 6];
                    },
                });
            });
  </script>
</head>
<body align="center">
  <form id="Form" onsubmit="runThis()">
    <input type="text" id="datepicker" value="YYYY-MM-DD"/>
    <input type="submit" value="Submit">
  </form>
  <script>
    function runThis() {
      alert("Hi!");
      google.script.run.doSomething();
    }
    </script>
</body>

</html>

Apps Script代码

function calendar() {
  var html = HtmlService.createHtmlOutputFromFile("CalendarInput");
  SpreadsheetApp.getUi().showModalDialog(html, "Choose the Monday start date from the calendar:");
}

function doSomething() {
  getMasterSpreadsheet().toast("hello");
  console.log("woohoo!");
  return true;
}

原因分析及解决办法

1. 表单默认提交行为中断请求

表单onsubmit触发后,默认会刷新模态框页面,导致google.script.run的服务器请求还未完成就被终止。

修复步骤:

  • 修改runThis()函数,阻止表单默认提交行为,同时传递选中的日期:
function runThis(e) {
  e.preventDefault(); // 阻止页面刷新
  const selectedDate = $("#datepicker").val();
  google.script.run
    .withSuccessHandler(() => {
      alert("提交成功");
      google.script.host.close(); // 关闭模态框
    })
    .withFailureHandler(err => alert("出错:" + err.message))
    .doSomething(selectedDate);
}
  • 同步修改HTML的form标签:
<form id="Form" onsubmit="runThis(event)">

2. 共享表格的权限/授权问题

共享环境下可能存在脚本授权过期、表格权限限制等问题:

  • 重新授权脚本:手动运行calendar()函数,完成授权流程,确保脚本拥有访问表格的权限
  • 检查getMasterSpreadsheet():如果该函数调用了其他表格,确认表格ID正确且当前用户有权限访问;可临时替换为SpreadsheetApp.getActiveSpreadsheet()测试是否正常
  • 查看执行日志:在Apps Script编辑器中点击「查看」→「执行日志」,查看是否有服务器端报错信息(HTTP 500通常对应后端代码异常)

3. 老旧依赖库的兼容性问题

你使用的jQuery 1.11.2和jQuery UI 1.11.3版本过旧,可能与当前Google Apps Script环境存在兼容性问题。

修复步骤:升级到稳定的新版本:

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/smoothness/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>

优化的日历选择实现方案

针对「仅允许选择周一」的需求,优化代码并确保日期格式规范:

优化后的HTML代码

<html>
<head>
  <title>选择日期</title>
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/smoothness/jquery-ui.css">
  <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>
  <script>
    $(function () {
      $("#datepicker").datepicker({
        dateFormat: "yy-mm-dd", // 强制输出YYYY-MM-DD格式
        beforeShowDay: d => [d.getDay() === 1], // 仅允许选择周一
        minDate: 0, // 可选今天及以后的日期
        maxDate: "+1m" // 限制未来1个月内的日期
      });
    });

    function submitDate(e) {
      e.preventDefault();
      const selectedDate = $("#datepicker").val();
      if (!selectedDate) {
        alert("请选择有效的周一日期");
        return;
      }
      google.script.run
        .withSuccessHandler(() => {
          alert("日期提交成功:" + selectedDate);
          google.script.host.close();
        })
        .withFailureHandler(err => alert("提交失败:" + err.message))
        .processSelectedDate(selectedDate);
    }
  </script>
  <style>
    body {padding: 20px; font-family: Arial, sans-serif;}
    #datepicker {padding: 8px; font-size: 14px; margin-right: 10px;}
    input[type="submit"] {
      padding: 8px 16px;
      background-color: #4285F4;
      color: white;
      border: none;
      border-radius: 4px;
      cursor: pointer;
    }
    input[type="submit"]:hover {background-color: #3367D6;}
  </style>
</head>
<body align="center">
  <form onsubmit="submitDate(event)">
    <input type="text" id="datepicker" placeholder="选择周一日期" required/>
    <input type="submit" value="提交">
  </form>
</body>
</html>

对应的Apps Script代码

function showCalendarModal() {
  var html = HtmlService.createHtmlOutputFromFile("CalendarInput")
    .setWidth(350)
    .setHeight(200);
  SpreadsheetApp.getUi().showModalDialog(html, "选择周一作为起始日期");
}

function processSelectedDate(selectedDate) {
  const ss = getMasterSpreadsheet();
  ss.toast("已选择日期:" + selectedDate);
  console.log("处理日期:", selectedDate);
  // 这里添加你的业务逻辑
}

// 确保表格获取逻辑正确
function getMasterSpreadsheet() {
  return SpreadsheetApp.getActiveSpreadsheet();
  // 若需访问其他表格,替换为:
  // return SpreadsheetApp.openById("你的表格ID");
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 21:34:54