Google Recaptcha V3多表单页面仅首个生效问题求助
解决多表单下Google Recaptcha V3仅首个表单生效的问题
你精准定位到了问题根源——HTML中id属性必须是唯一的,document.getElementById('recaptchaResponse')只会找到页面中第一个匹配该id的元素,所以第二个表单的隐藏输入框永远拿不到验证token。下面给你两种可行的修复方案,按需选择:
方案1:提交表单时动态生成并注入Token(推荐)
这种方法不仅解决了多表单的问题,还能避免页面加载时生成的Token过期(Recaptcha V3 Token有效期约2分钟),更符合最佳实践:
修改后的JavaScript代码
<script src="https://www.google.com/recaptcha/api.js?render=你的站点密钥"></script> <script> // 给所有带user类的表单绑定提交事件 document.querySelectorAll('form.user').forEach(form => { form.addEventListener('submit', function(e) { // 先阻止默认提交行为,等拿到Token再提交 e.preventDefault(); const currentForm = this; grecaptcha.ready(function () { grecaptcha.execute('你的站点密钥', { action: 'contact' }).then(function (token) { // 找到当前提交表单内的recaptcha_response隐藏域 const recaptchaInput = currentForm.querySelector('input[name="recaptcha_response"]'); recaptchaInput.value = token; // 完成Token注入后,提交表单 currentForm.submit(); }); }); }); }); </script>
表单代码修改(移除重复id)
把两个表单里的id="recaptchaResponse"删掉,保留name属性即可(后端接收验证时靠name取值):
<form class="user" action="" method="post" name="form1" id="form1"> <input type="hidden" name="source" value="form1"> <button type="submit" class="btn btn-success">Submit 1</button> <input type="hidden" name="recaptcha_response"> </form> <form class="user" action="" method="post" name="form2" id="form2"> <input type="hidden" name="source" value="form2"> <button type="submit" class="btn btn-success">Submit 2</button> <input type="hidden" name="recaptcha_response"> </form>
方案2:页面加载时给每个表单的唯一隐藏域赋值Token
如果你偏好页面加载时就生成Token,那给每个隐藏域设置唯一id,然后分别赋值:
JavaScript代码
<script src="https://www.google.com/recaptcha/api.js?render=你的站点密钥"></script> <script> grecaptcha.ready(function () { grecaptcha.execute('你的站点密钥', { action: 'contact' }).then(function (token) { // 给第一个表单的隐藏域赋值 document.getElementById('recaptchaResponse1').value = token; // 给第二个表单的隐藏域赋值 document.getElementById('recaptchaResponse2').value = token; }); }); </script>
表单代码(设置唯一id)
<form class="user" action="" method="post" name="form1" id="form1"> <input type="hidden" name="source" value="form1"> <button type="submit" class="btn btn-success">Submit 1</button> <input type="hidden" name="recaptcha_response" id="recaptchaResponse1"> </form> <form class="user" action="" method="post" name="form2" id="form2"> <input type="hidden" name="source" value="form2"> <button type="submit" class="btn btn-success">Submit 2</button> <input type="hidden" name="recaptcha_response" id="recaptchaResponse2"> </form>
⚠️ 注意:方案2的Token会在页面加载时生成,若用户停留页面超过2分钟再提交,Token会失效导致验证失败,所以更推荐方案1。
内容的提问来源于stack exchange,提问作者Ingus
相关产品推荐
相关产品推荐

