Google表格客户端与服务端通信问题:google.script.run失效
问题分析与修复方案
核心问题点
- 废弃API导致加载错误:
setSandboxMode(HtmlService.SandboxMode.NATIVE)是已被移除的旧版API,会触发对话框加载时的TransportError。 - DOM结构异常:HTML表单标签未闭合,引发提交时的Uncaught错误。
- 提交逻辑冗余:同时绑定
onsubmit事件和全局preventFormSubmit监听,可能导致冲突。
修正后的代码
Code.gs
function addMenuItem() { SpreadsheetApp.getUi() .createMenu('My Functions') .addItem('Show Dialog', 'showModal') .addToUi(); } function showModal() { // 移除废弃的沙箱模式配置,使用默认设置即可 const userInterface = HtmlService.createHtmlOutputFromFile('modal'); SpreadsheetApp.getUi().showModelessDialog(userInterface, 'My modal'); } function processForm(formObject) { var formName = formObject.name; SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1').appendRow([formName]); return "success"; }
modal.html
<!DOCTYPE html> <html> <head> <base target="_top"> <link href="https://fonts.googleapis.com/css2?family=Comic+Neue&display=swap" rel="stylesheet"> <style> * { font-family: 'Comic Neue', cursive; } input { font-size: 18px; outline: none; padding: 5px; margin-bottom: 10px; } button { cursor: pointer; /* 修正cursor属性错误,原select不符合按钮交互逻辑 */ outline: none; font-size: 18px; padding: 7px 15px; background-color: #57ff87; border-radius: 5px; box-shadow: 0 2px 3px #5555; } button:active { filter: brightness(1.2); box-shadow: 0 2px 3px #5550; } </style> <script> function handleFormSubmit(formObject) { google.script.run .withSuccessHandler(function(response) { alert("内容已成功添加"); google.script.host.close(); }) .withFailureHandler(function(error) { alert("提交失败:" + error.message); }) .processForm(formObject); return false; // 阻止表单默认提交行为 } </script> </head> <body> <h1>Hello, and Welcome!</h1> <!-- 闭合form标签,修正onsubmit逻辑 --> <form id="myForm" onsubmit="return handleFormSubmit(this)"> <input name="name" type="text" placeholder="请输入内容" /> <input type="submit" value="Submit" /> </form> </body> </html>
额外优化说明
- 新增成功/失败回调,提升用户反馈体验。
- 修正按钮光标样式,符合交互预期。
- 给输入框添加占位提示,增强易用性。
内容的提问来源于stack exchange,提问作者Yunlong
相关产品推荐
相关产品推荐

