Google Sheets Workspace插件:更新userProperty后自动刷新UI的方法
解决Google Workspace插件提交设置后自动更新UI的问题
一、修复contextualTriggers的清单配置错误
你遇到的「Invalid manifest: unknown fields: [addOns.common.contextualTriggers]」错误,是因为contextualTriggers字段的位置配置错误。当前版本的Google Workspace插件清单中,该字段不能放在addOns.common下,需要根据插件对应的服务(如Gmail、Docs、Sheets等)放在专属的服务节点内。
以Gmail插件为例,正确的appsscript.json配置片段:
{ "timeZone": "Asia/Shanghai", "runtimeVersion": "V8", "addOns": { "common": { "name": "设置演示插件", "logoUrl": "https://your-logo-url.png", "layoutProperties": { "primaryColor": "#4285F4" } }, "gmail": { "contextualTriggers": [ { "unconditional": {}, "onTriggerFunction": "buildMainCard" } ] } } }
二、无需手动刷新自动更新UI的正确实现
使用ActionResponseBuilder结合updateCard是正确的方案,你之前可能是在响应逻辑上有疏漏,以下是完整可运行的实现示例:
Code.gs核心代码
// 构建主卡片(加载当前设置) function buildMainCard() { // 从用户属性中读取已保存的设置 const userProps = PropertiesService.getUserProperties(); const savedValue = userProps.getProperty('userPreference') || '默认值'; // 构建输入控件 const inputWidget = CardService.newTextInput() .setFieldName('userPreference') .setValue(savedValue) .setTitle('我的偏好设置'); // 构建保存按钮,绑定处理函数 const saveBtn = CardService.newTextButton() .setText('保存设置') .setOnClickAction(CardService.newAction().setFunctionName('handleSaveSettings')); // 组装卡片 const cardSection = CardService.newCardSection() .addWidget(inputWidget) .addWidget(saveBtn); return CardService.newCardBuilder().addSection(cardSection).build(); } // 处理设置保存并返回更新后的卡片 function handleSaveSettings(e) { // 获取提交的表单值 const newPreference = e.formInput.userPreference; // 保存到用户属性 PropertiesService.getUserProperties().setProperty('userPreference', newPreference); // 重新构建包含新设置的卡片 const updatedCard = buildMainCard(); // 返回更新卡片的响应,触发UI自动刷新 return CardService.newActionResponseBuilder() .setNavigation(CardService.newNavigation().updateCard(updatedCard)) .build(); }
关键注意事项
- 所有UI更新必须通过服务器端返回新卡片实现,客户端无法直接修改卡片内容
- 确保处理设置的函数必须返回
ActionResponse对象,不能返回其他类型 - 测试时要部署最新版本的插件,避免缓存导致的旧代码运行
- 如果需要刷新整个插件的根卡片,可以替换为
CardService.newNavigation().popToRoot().pushCard(updatedCard)
内容的提问来源于stack exchange,提问作者Let Me Tink About It
相关产品推荐
相关产品推荐

