如何使用JavaScript动态生成Google reCaptcha验证div元素
Google reCaptcha 动态生成实现方案
核心实现逻辑
- 避免重复加载reCaptcha官方API脚本
- 动态生成表单、验证码容器、提交按钮的DOM结构
- 兼容API加载完成前/完成后的两种渲染场景
完整实现代码
/** * 动态生成reCaptcha验证组件 * @param {string} siteKey 你申请的reCaptcha站点密钥 * @param {HTMLElement} target 要插入组件的父容器 */ function generateReCaptcha(siteKey, target) { // 加载reCaptcha API脚本,避免重复加载 if (!$('script[src="https://www.google.com/recaptcha/api.js"]').length) { const captchaScript = document.createElement('script'); captchaScript.src = 'https://www.google.com/recaptcha/api.js'; captchaScript.async = true; captchaScript.defer = true; document.head.appendChild(captchaScript); } // 构建表单和验证码相关DOM const form = $('<form>', { action: '?', method: 'POST' }); const captchaWrap = $('<div>').addClass('g-recaptcha').attr('data-sitekey', siteKey); const submitBtn = $('<input>').attr({ type: 'submit', value: 'Submit' }); // 组装DOM插入到目标容器 form.append(captchaWrap).append('<br/>').append(submitBtn); $(target).append(form); // 若API已加载完成,手动触发验证码渲染 if (window.grecaptcha) { grecaptcha.render(captchaWrap[0], { sitekey: siteKey }); } }
使用示例
将代码中的your_site_key替换为自己的站点密钥,调用函数即可插入组件:
// 示例:将验证码组件插入到页面body中 generateReCaptcha('your_site_key', document.body);
注意事项
- 站点密钥需要和绑定的域名对应才能正常使用
- 组件插入后如果没有正常渲染,可检查API脚本是否加载成功、站点密钥是否正确
- 表单提交后,后端需要获取
g-recaptcha-response参数,调用reCaptcha服务端接口校验验证结果,才算完成完整的验证流程
内容的提问来源于stack exchange,提问作者Doyel Mishra
相关产品推荐
相关产品推荐

