解决Google App Script Legacy模式下includes报错及菜单生成异常问题
解决方案
核心修改点
- Legacy Rhino运行时不支持ES6+的API,
Array.prototype.includes()方法不存在,需要替换为兼容的Array.indexOf()方法 - 之前替换
indexOf后排除逻辑失效的原因:indexOf匹配到元素时返回对应下标(匹配到第一个排除项onOpen时返回0),!0的布尔值为true,反而会把要排除的函数加入菜单,需要明确判断返回值等于-1时才是不在排除列表内 - 补充
this.hasOwnProperty(i)判断,避免for-in循环遍历到原型链上的异常函数,逻辑更稳妥
完整可运行代码
function installFunctions() { var excludedFunctions = ["onOpen", "installFunctions"]; var menu = SpreadsheetApp.getUi().createMenu('Funções do GAS'); for (var i in this) { if (typeof this[i] == "function" && this.hasOwnProperty(i) && excludedFunctions.indexOf(i) === -1) { menu.addItem(i, i); } } menu.addToUi(); } function onOpen() { installFunctions(); } function ClimaParaTestes() { } function JogosParaClimaParaTestes() { } function EnviarClimasParaSquads() { } function ApagarHistoricoDoClima() { } function deleteTriggerWithName(name) { }
上述代码可直接在Legacy模式下正常运行,生成的菜单会自动过滤排除列表内的函数,仅展示自定义的业务函数。
内容的提问来源于stack exchange,提问作者Digital Farmer
相关产品推荐
相关产品推荐

