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

Google Apps Script:如何向模态窗口传递及回传变量?

Google Sheets插件模态窗口变量传递方案

向模态窗口传递变量

有两种实用方案,按需选择:

1. 模板直接注入变量(适合静态/初始化变量)

通过HtmlService模板语法,在服务端直接把变量嵌入弹窗HTML:
服务端GS代码:

function showSearchDialog() {
  // 准备要传递的变量(可从工作表/配置中动态获取)
  const dialogData = {
    options: ["选项1", "选项2", "选项3"],
    customTitle: "请选择操作"
  };
  // 用模板文件创建输出并注入变量
  const template = HtmlService.createTemplateFromFile('searchScreen');
  template.dialogData = dialogData;
  const htmlOutput = template.evaluate().setWidth(400).setHeight(520);
  SpreadsheetApp.getUi().showModalDialog(htmlOutput, 'Select option');
}

弹窗searchScreen.html中使用变量:

<!DOCTYPE html>
<html>
<body>
  <h3><?= dialogData.customTitle ?></h3>
  <select id="optionSelect">
    <? // 遍历变量生成选项 ?>
    <? dialogData.options.forEach(option => { ?>
      <option value="<?= option ?>"><?= option ?></option>
    <? }) ?>
  </select>
</body>
</html>

说明:<?= ?>用于输出变量,<? ?>用于执行模板逻辑,都是HtmlService原生语法

2. 弹窗加载后动态获取(适合实时/动态数据)

通过google.script.run调用服务端函数拉取数据:
服务端GS新增函数:

function getDialogOptions() {
  // 示例:从工作表A1:A3读取选项
  return SpreadsheetApp.getActiveSheet().getRange("A1:A3").getValues().flat();
}

弹窗searchScreen.html中添加脚本:

<script>
window.onload = () => {
  google.script.run
    .withSuccessHandler(options => {
      // 拿到数据后渲染下拉框
      const select = document.getElementById('optionSelect');
      options.forEach(opt => {
        const option = document.createElement('option');
        option.value = opt;
        option.textContent = opt;
        select.appendChild(option);
      });
    })
    .getDialogOptions();
};
</script>

从模态窗口回传变量到服务端

核心用google.script.run调用服务端处理函数,同时支持成功/失败回调:
弹窗searchScreen.html添加确认按钮及脚本:

<button onclick="submitSelection()">确认选择</button>
<script>
function submitSelection() {
  const selectedVal = document.getElementById('optionSelect').value;
  google.script.run
    .withSuccessHandler(() => {
      // 成功后关闭弹窗
      google.script.host.close();
    })
    .withFailureHandler(err => alert('提交失败:' + err.message))
    .processSelectedValue(selectedVal);
}
</script>

服务端GS新增处理函数:

function processSelectedValue(selected) {
  // 示例:把选中值写入工作表B1单元格
  SpreadsheetApp.getActiveSheet().getRange("B1").setValue(selected);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 16:39:58