Shopify表单提交后重定向至script.googleusercontent且无成功弹窗问题
问题:Shopify表单提交后自动重定向,成功提示弹窗失效
我在Shopify页面上部署了一个简单表单,HTML代码如下:
<div class="form-container"> <form id="giveaway-form" method="POST" action="https://script.google.com/macros/s/MY-WEB-APP-URL/exec" > <div class="form-row"> <input type="text" name="first_name" placeholder="First Name" required> <input type="text" name="last_name" placeholder="Last Name" required> </div> <button type="submit" value="Submit">Submit</button> </form>
搭配的脚本原本会在表单提交成功时弹出提示框:
window.addEventListener("load", function() { const form = document.getElementById('giveaway-form'); form.addEventListener("submit", function(e) { e.preventDefault(); const data = new FormData(form); const action = e.target.action; fetch(action, { method: 'POST', body: data, }) .then(() => { alert("Success!"); }) }); });
该功能在9月5日还能正常运行,目前表单数据仍可存入Google Sheets,但提交后会重定向至script.googleusercontent页面,成功提示弹窗也不再显示。

解决方法
核心原因
问题出在Google Apps Script Web App的默认响应会触发页面重定向,同时前端脚本可能因为事件绑定失效或未正确处理响应,导致e.preventDefault()没有完全阻止默认提交行为。
具体修复步骤
强化前端事件阻止逻辑
改用DOMContentLoaded确保脚本在DOM就绪后执行,同时添加事件冒泡阻止,避免Shopify主题脚本干扰:document.addEventListener("DOMContentLoaded", function() { const form = document.getElementById('giveaway-form'); if (!form) return; form.addEventListener("submit", function(e) { e.preventDefault(); e.stopPropagation(); // 阻止事件被其他脚本捕获 const data = new FormData(form); fetch(form.action, { method: 'POST', body: data, }) .then(response => { if (response.ok) { alert("提交成功!"); form.reset(); } else { throw new Error('响应异常'); } }) .catch(err => { console.error(err); alert("提交失败,请稍后重试"); }); }); });修改Google Apps Script返回值
在你的Web App脚本中,返回纯文本响应而非默认HTML,彻底避免重定向:function doPost(e) { // 写入Google Sheets的逻辑 const ss = SpreadsheetApp.openById('你的表格ID'); const sheet = ss.getSheetByName('Sheet1'); sheet.appendRow([e.parameter.first_name, e.parameter.last_name]); // 返回纯文本成功响应 return ContentService.createTextOutput("提交成功") .setMimeType(ContentService.MimeType.TEXT); }验证脚本加载位置
将你的JS脚本放在表单元素的下方(而非页面头部),确保DOM元素已加载完成,避免找不到表单元素的情况。
内容的提问来源于stack exchange,提问作者Conor
相关产品推荐
相关产品推荐

