You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google reCaptcha的data-callback属性导致弹窗后页面刷新问题

表单集成reCaptcha v3后的验证问题解决

问题根源

你遇到的问题是因为reCaptcha v3的自动回调机制会绕过自定义验证和原生required属性校验——哪怕你在onClick里返回false,reCaptcha的内部逻辑还是会继续触发data-callback里的表单提交,导致弹窗后页面依然刷新提交。

修复方案

直接调整流程,把自定义验证放在最前面,验证通过后再手动触发reCaptcha,具体步骤如下:

  • 把提交按钮改成普通按钮(type="button"),避免原生表单提交事件干扰
  • 先做原生表单验证(让required生效),再做自定义验证,全部通过后才调用reCaptcha验证
  • 移除data-callback和g-recaptcha类的自动触发逻辑,改为手动控制reCaptcha流程

修改后的完整代码

<html>
<head> 
<script src="https://www.google.com/recaptcha/api.js"></script>
<script>
  // reCaptcha验证通过后再提交表单
  function onSubmit(token) {
    document.getElementById("demo-form").submit();
  }

  // 先验证,再触发reCaptcha
  function validateAndSubmit() {
    const form = document.getElementById("demo-form");
    
    // 先触发原生required验证
    if (!form.checkValidity()) {
      form.reportValidity(); // 显示原生提示,也可以换成你自己的alert
      return;
    }

    // 自定义额外验证
    const fname = document.forms.WebForm.fname.value;
    if (fname.trim() === "") {
      alert("Please fill out all the fields");
      return;
    }

    // 所有验证通过,调用reCaptcha执行验证
    grecaptcha.execute('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', {action: 'submit'}).then(onSubmit);
  }
</script>
</head>
<body>
  <div class="container">
    <form action="https://www.samepage.com" method="post" id="demo-form" name="WebForm">
      <div>         
        <div>
          <input name="fname" id="fname" type="text" placeholder="First name*" required/>
        </div>
      </div>
      <div>
        <div>
          <!-- 换成普通按钮,绑定自定义验证函数 -->
          <input type="button" style="font-weight: bold;" value="Submit" class="button" onclick="validateAndSubmit()"/>
        </div>
      </div>
    </form>
  </div>
</body>
</html>

改动说明

  1. 按钮类型调整:不再用type="submit",彻底切断原生表单提交的触发路径,所有流程由自定义代码控制
  2. 验证顺序优化:先跑原生required验证,再跑你的自定义验证,任何一步不通过都终止流程,不会触发reCaptcha
  3. 手动调用reCaptcha:只有所有验证通过后,才调用grecaptcha.execute触发reCaptcha验证,验证通过后再执行表单提交

这样修改后,验证不通过时不会提交表单,弹窗后页面也不会刷新;required属性能正常工作,提交按钮也不会失效。

内容的提问来源于stack exchange,提问作者Vishnu Ravindren

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 16:36:11