Google Apps Script表单预填与用户邮箱获取问题咨询
问题描述
我通过以下doGet脚本将当前用户邮箱传递至嵌入iframe的Google表单,表单由onOpen脚本触发:
function doGet(e) { const email = Session.getActiveUser().getEmail(); if (!email) { return HtmlService.createHtmlOutput('<h1>Access Denied</h1><p>You must be signed in to access this form.</p>'); } const preFilledFormUrl = generatePreFilledFormUrl(email); return HtmlService.createHtmlOutput(` <!DOCTYPE html> <html> <body> <h1>Google Form</h1> <p>Benvenuto, ${email}</p> <iframe src="${preFilledFormUrl}" width="100%" height="800"></iframe> </body> </html> `); } function generatePreFilledFormUrl(email) { const formUrl = "https://docs.google.com/forms/d/e/1FAIpQLSepCWXuUFt3oKXBlsLWBurnSl_vuleGAu6gSIKr87bT3vOAaA/viewform"; const fieldKey = "entry.335126256"; // this is the ID of the form item "email" return `${formUrl}?${fieldKey}=${encodeURIComponent(email)}`; }
Google自动在表单中插入了一个包含调用用户正确邮箱的新项。现存在两个问题:
- 是否可以获取该自动插入项的邮箱值?
doGet传递URL中指定ID为entry.335126256的表单项未被预填邮箱,通过以下getResponse查询无对应值,请问原因是什么?还有其他获取传递邮箱的方法吗?
查询用的代码:
var form = FormApp.getActiveForm(); const formResponses = form.getResponses(); for (let i = 0; i < formResponses.length; i++) { const formResponse = formResponses[i]; const itemResponses = formResponse.getItemResponses(); for (let j = 0; j < itemResponses.length; j++) { const itemResponse = itemResponses[j]; Logger.log( 'Response #%s to the question "%s" was "%s"', (i + 1).toString(), itemResponse.getItem().getTitle(), itemResponse.getResponse(), ); } }
问题解答
1. 能否获取Google自动插入的邮箱项的值?
可以获取。这个自动插入的邮箱项是表单**「收集电子邮件地址」功能**生成的,有两种获取方式:
- 在表单绑定的响应表格(Google Sheets)中,该邮箱会作为单独一列显示,列标题通常为「受访者电子邮件」;
- 通过Google Apps Script的
FormResponse对象直接调用getRespondentEmail()方法获取,无需遍历所有表单项:var form = FormApp.getActiveForm(); const formResponses = form.getResponses(); formResponses.forEach((response, index) => { Logger.log('Response #%s 的受访者邮箱:%s', index+1, response.getRespondentEmail()); });
2. 预填邮箱失效的原因及替代方案
失效原因
常见问题有三个:
entry.xxx字段ID错误:表单字段的entryID会在编辑表单时(比如修改字段类型、删除重建字段)发生变化,需要重新确认正确的字段ID。获取方式:打开表单的预填链接,手动输入邮箱后生成的链接中,对应邮箱字段的参数就是正确的entry.xxx;- iframe跨域限制:Google Forms通过iframe加载时,可能会忽略URL中的预填参数(尤其是脚本部署为Web应用时,跨域策略可能导致参数丢失);
- 表单设置限制:如果表单开启了「仅特定用户可填写」,预填参数可能被表单的身份验证逻辑覆盖。
替代获取邮箱的方法
有两种更可靠的方案:
方式一:利用表单内置的「收集电子邮件地址」功能
在表单设置中开启**「收集电子邮件地址」**(设置→常规→收集电子邮件地址),表单会自动收集登录用户的邮箱,无需通过脚本传递,且可以通过response.getRespondentEmail()直接获取,这是最稳定的方案。
方式二:通过Web应用脚本直接关联响应与邮箱
如果必须通过脚本传递邮箱,可以在用户提交表单时绑定邮箱与响应:
- 修改
doGet脚本,在iframe的URL中添加自定义参数,比如userEmail=${email}; - 为表单添加
onFormSubmit触发器,在触发函数中通过e.response.getId()获取响应ID,再结合PropertiesService或Google Sheets临时存储的邮箱完成关联; - 或者在Web应用中监听表单提交事件,将邮箱和响应数据一起写入指定的Sheets中,绕过表单本身的响应收集限制。
内容的提问来源于stack exchange,提问作者David Harris
相关产品推荐
相关产品推荐

