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

Google Recaptcha v2在模态框表单中始终返回空白响应求助

解决模态框中reCAPTCHA返回空白的问题

这个问题的核心原因很明确:reCAPTCHA初始化时,容器必须处于可见状态。你的模态框默认是隐藏的(通常是display: none),页面加载时reCAPTCHA尝试初始化,但找不到可见的容器,导致整个验证组件没有正常工作,所以grecaptcha.getResponse()会返回空字符串。

具体解决步骤:

  1. 先修改模态框里的reCAPTCHA容器,去掉data-sitekey属性,只保留容器ID:
<div id="recaptcha-container" class="g-recaptcha"></div>
  1. 在打开模态框的函数中,等模态框显示后手动初始化reCAPTCHA:
function openAddReviewPopup() {
  // 显示模态框的原有代码
  document.getElementById('addReviewPopup').style.display = 'block';
  
  // 手动渲染reCAPTCHA,保存实例ID方便后续操作
  window.recaptchaId = grecaptcha.render('recaptcha-container', {
    sitekey: '6LeVWpAqAAAAAIoVEEJNTY4S5L4larqFsRLpjX16'
  });
}
  1. 关闭模态框时销毁旧的reCAPTCHA实例,避免重复渲染:
function closePopup(popupId) {
  document.getElementById(popupId).style.display = 'none';
  
  // 销毁已存在的reCAPTCHA实例
  if (window.recaptchaId) {
    grecaptcha.reset(window.recaptchaId);
    grecaptcha.destroy(window.recaptchaId);
    window.recaptchaId = null;
  }
}
  1. 表单提交时通过实例ID获取验证码响应:
document.getElementById('addReviewForm').addEventListener('submit', function(e) {
  e.preventDefault();
  
  const response = grecaptcha.getResponse(window.recaptchaId);
  if (!response) {
    alert('请完成验证码验证');
    return;
  }
  
  // 这里继续处理表单提交逻辑
});

额外提示:

  • 确保页面已正确引入reCAPTCHA脚本:<script src="https://www.google.com/recaptcha/api.js"></script>
  • 绝对不要在页面加载时自动初始化模态框内的reCAPTCHA,必须等容器可见后再手动渲染。

内容的提问来源于stack exchange,提问作者Shreyas Kulkarni

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 21:28:11