Google App Script跨函数传动态变量:表单触发后取值异常求助
问题:时间触发器传递参数失败导致Script Properties取值为空
问题现象
运行代码时,firstLetter函数中:
Logger.log(propertyKey)输出timestamp_[object Object]Logger.log(email)输出null
当前代码流程
- 表单提交触发
formResponse函数 - 从表单响应中提取时间戳和邮箱
- 将时间戳作为键、邮箱作为值存入Script Properties
- 创建延迟10秒的时间触发器,调用
firstLetter函数
核心需求
firstLetter必须在对应表单提交的formResponse执行后运行,且仅处理该次提交的邮箱数据,支持多人同时提交。
问题原因
时间触发器触发函数时,不会自动传递自定义参数,firstLetter中的timestamp参数实际接收的是触发器的事件对象(而非预期的时间戳字符串),因此拼接键名时会将对象转为[object Object],导致无法匹配到Script Properties中存储的键。
解决方案
通过触发器的setDescription()方法将时间戳存入触发器描述,在firstLetter函数中从事件对象提取该描述,即可获取对应提交的时间戳。同时处理完数据后删除对应触发器,避免冗余资源占用。
修改后的代码
function formResponse(e) { const timestamp = e.values[0]; const email = e.values[1]; const propertyKey = `timestamp_${timestamp}`; PropertiesService.getScriptProperties().setProperty(propertyKey, email); // 创建触发器时将时间戳存入描述 ScriptApp.newTrigger('firstLetter') .timeBased() .after(10000) .setDescription(timestamp) .create(); } function firstLetter(e) { // 从触发器事件对象中获取描述(即时间戳) const timestamp = e.trigger.getDescription(); const propertyKey = `timestamp_${timestamp}`; Logger.log(propertyKey); const email = PropertiesService.getScriptProperties().getProperty(propertyKey); Logger.log(email); if (email) { const firstL = email.charAt(0); Logger.log(`First letter of email: ${firstL}`); // 删除属性和对应的触发器 PropertiesService.getScriptProperties().deleteProperty(propertyKey); ScriptApp.deleteTrigger(e.trigger); } else { Logger.log('Email not found for the given timestamp.'); // 清理无效触发器 ScriptApp.deleteTrigger(e.trigger); } }
内容的提问来源于stack exchange,提问作者S Inversin Social y Alianzas E
相关产品推荐
相关产品推荐

