Gmail Apps Script插件中CardService.newAlert()调用失败求助
问题:Gmail Apps Script插件按钮点击触发TypeError错误
插件启动正常,但点击按钮时始终触发错误:
TypeError: CardService.newAlert is not a function.
问题原因
Gmail插件的CardService不支持newAlert()方法,该方法仅适用于Google Docs、Sheets等其他Workspace应用的插件。Gmail插件需要使用newNotification()来创建用户提示。
修改后的完整代码
JavaScript 脚本
/** * 插件打开时调用的主函数,创建包含两个按钮的插件界面。 * @param {Object} e 包含上下文信息的事件对象。 * @return {Card} 代表插件UI的卡片。 */ function onOpen(e) { const cardBuilder = CardService.newCardBuilder(); const section = CardService.newCardSection().setHeader('选择操作'); const halloButton = CardService.newTextButton() .setText('Hallo') .setOnClickAction(CardService.newAction().setFunctionName('showAlertHallo')); const fertigButton = CardService.newTextButton() .setText('Fertig') .setOnClickAction(CardService.newAction().setFunctionName('showAlertFertig')); section.addWidget(halloButton); section.addWidget(fertigButton); cardBuilder.addSection(section); return cardBuilder.build(); } /** * 点击“Hallo”按钮时调用的函数,创建显示“Hallo”的通知。 * @return {ActionResponse} 显示通知的响应。 */ function showAlertHallo() { const notification = CardService.newNotification() .setText('Hallo') .setType(CardService.NotificationType.INFO); return CardService.newActionResponseBuilder().setNotification(notification).build(); } /** * 点击“Fertig”按钮时调用的函数,创建显示“Fertig”的通知。 * @return {ActionResponse} 显示通知的响应。 */ function showAlertFertig() { const notification = CardService.newNotification() .setText('Fertig') .setType(CardService.NotificationType.SUCCESS); return CardService.newActionResponseBuilder().setNotification(notification).build(); }
appsscript.json(无需修改)
{ "timeZone": "Europe/Berlin", "dependencies": { }, "exceptionLogging": "STACKDRIVER", "runtimeVersion": "V8", "addOns": { "common": { "name": "Stefans Add-on", "logoUrl": "https://www.gstatic.com/images/icons/material/system/2x/label_googblue_48dp.png" }, "gmail": { "contextualTriggers": [{ "unconditional": { }, "onTriggerFunction": "onOpen" }] } } }
修改说明
- 替换提示创建方法:将
CardService.newAlert()改为CardService.newNotification(),这是Gmail插件支持的提示方式。 - 调整响应设置:
ActionResponseBuilder的setAlert()替换为setNotification(),匹配新的提示对象。 - 可选优化:添加
setType()设置通知类型(如INFO、SUCCESS),让提示样式更符合Gmail插件的交互规范。
内容的提问来源于stack exchange,提问作者J. Doe
相关产品推荐
相关产品推荐

