如何通过独立Apps Script插件为Google Sheets注册自定义函数
解决方案
核心原因说明
你之前使用的旧方案失效是因为Google后续收紧了独立Workspace插件的作用域授权逻辑:独立插件的简单onOpen触发无法获得足够权限将自定义函数挂载到当前表格的运行上下文,同时缺少必须的清单声明配置,导致自定义函数无法被表格识别。
第一步:修正清单文件(appsscript.json)配置
在项目中打开清单文件,添加Sheets自定义函数声明和必须的授权范围,参考配置如下:
{ "timeZone": "你所在的时区,比如Asia/Shanghai", "dependencies": {}, "exceptionLogging": "STACKDRIVER", "runtimeVersion": "V8", "oauthScopes": [ "https://www.googleapis.com/auth/spreadsheets.currentonly", "https://www.googleapis.com/auth/script.container.ui" ], "addOns": { "common": { "name": "你的插件名称", "logoUrl": "你的插件logo公开地址", "homepageTrigger": { "runFunction": "buildHomePage", "enabled": true } }, "sheets": { "customFunctions": { "runFunction": "getCustomFunctions" } } } }
第二步:补全注册逻辑代码
添加自定义函数声明、卡片交互和注册相关的代码,参考示例如下:
// 你已有的自定义函数,保持@customfunction注释即可,函数名必须全大写 /** * 示例自定义函数 * @param {string} input 输入参数 * @return {string} 处理结果 * @customfunction */ function MY_CUSTOM_FUNC(input) { return "处理结果:" + input; } // 清单中customFunctions对应的声明函数,返回所有要注册的自定义函数引用 function getCustomFunctions() { return [ MY_CUSTOM_FUNC // 你有其他自定义函数依次加在这里即可 ]; } // 首页卡片生成函数,对应清单里的homepageTrigger配置 function buildHomePage() { const card = CardService.newCardBuilder(); const section = CardService.newCardSection(); const enableAction = CardService.newAction().setFunctionName("enableFunc"); section.addWidget(CardService.newTextButton().setText("启用自定义函数").setOnClickAction(enableAction)); card.addSection(section); return card.build(); } // 按钮点击回调函数,仅用于触发用户主动授权,不需要额外业务逻辑 function enableFunc() { return CardService.newActionResponseBuilder() .setNotification(CardService.newNotification().setText("启用成功,刷新表格即可使用自定义函数")) .build(); }
第三步:验证生效流程
- 重新创建测试部署,覆盖之前的测试版本
- 打开目标Google表格,重新安装测试版本插件
- 点击右侧插件栏的对应插件图标,打开侧边栏卡片
- 点击「启用自定义函数」按钮,收到成功提示后刷新当前表格
- 在单元格输入你的自定义函数名即可正常调用,同时会显示你配置的智能提示
内容的提问来源于stack exchange,提问作者So8res
相关产品推荐
相关产品推荐

