如何通过GoogleForm的OnSubmit事件结合Iframe在站点展示GoogleDrive的PDF
实现步骤
前置配置
- 首先将Google Form的提交结果绑定到关联的Google Sheet,确认用户输入名称字段的列位置(第一列索引为0,第二列为1,以此类推)
- 打开Google Sheet的「扩展程序」-「Apps Script」,粘贴以下代码,替换其中的占位参数:
function onFormSubmit(e) { // 替换为你的Google Sites页面地址 const targetPage = "https://sites.google.com/你的站点页面路径"; // 替换为名称字段对应的列索引,示例为第一列 const submitName = e.values[0]; const targetPdfName = `${submitName}.PDF`; // 替换为你存储PDF的Google Drive文件夹ID const pdfFolder = DriveApp.getFolderById("你的Drive文件夹ID"); const matchFiles = pdfFolder.getFilesByName(targetPdfName); if (matchFiles.hasNext()) { const pdfFile = matchFiles.next(); // 自动设置文件为公开可查看,也可提前批量设置权限后删除这行 pdfFile.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW); const previewUrl = pdfFile.getUrl().replace("/view", "/preview"); // 跳转回站点页面并传递预览地址参数 return HtmlService.createHtmlOutput(`<script>window.top.location.href = '${targetPage}?pdf=${encodeURIComponent(previewUrl)}';</script>`); } else { return HtmlService.createHtmlOutput(`<script>window.top.location.href = '${targetPage}?error=not_found';</script>`); } }
- 在Apps Script编辑器左侧选择「触发器」,新建触发器:选择事件源为「电子表格」,事件类型为「表单提交时」,保存后按照提示完成权限授权
- 回到Google Form设置页,关闭「提交后发送响应副本」选项,避免默认提示拦截跳转
前端代码修改
替换原有页面的逻辑代码即可:
<!-- 表单嵌入代码 --> <iframe id="gform" src="https://docs.google.com/forms/d/e/NEWFORMID/viewform?embedded=true" width="640" height="427" frameborder="0" marginheight="0" marginwidth="0">Loading..</iframe> <!-- PDF预览容器 --> <iframe id="pdf_preview" width="100%" height="800" frameborder="0" style="display: none;"></iframe> <script type="text/javascript"> // 读取URL参数 function getQueryVal(name) { return new URLSearchParams(window.location.search).get(name); } const pdfUrl = getQueryVal('pdf'); const errMsg = getQueryVal('error'); if (pdfUrl) { // 提交成功,隐藏表单显示PDF document.getElementById('gform').style.display = 'none'; const previewIframe = document.getElementById('pdf_preview'); previewIframe.src = decodeURIComponent(pdfUrl); previewIframe.style.display = 'block'; } else if (errMsg) { alert('未找到匹配的PDF文件,请检查提交的名称是否正确'); } </script>
注意事项
- 确保存储PDF的Google Drive文件夹对运行Apps Script的账号(一般为表单所有者账号)开放编辑权限
- 如果文件名可能重复,建议给PDF文件添加唯一标识作为文件名,避免匹配错误
- 若不需要每次提交都自动设置文件权限,可提前批量将所有PDF设置为「知道链接的任何人可查看」,删除代码中
setSharing相关行即可
内容的提问来源于stack exchange,提问作者auto form
相关产品推荐
相关产品推荐

