reference error: grecaptcha is undefined in chrome

reference error: grecaptcha is undefined in chrome

我在同一张表格上有两个验证码。一个在提交上,另一个在模态上,将在表单提交后打开。所以我在阅读了这里的许多答案后渲染了它。现在它在 mozilla 上工作正常,但在 chrome.

中出现引用错误

我的 google api 是:

<script src='https://www.google.com/recaptcha/api.js'></script>

然后我的代码在 java 脚本中呈现它:

$('.g-recaptcha').each(function(index, el) {
        widgetId = grecaptcha.render(el, {'sitekey' : 'My-SITE-KEY'});
});

我的html是这样读的

<div id="user_recaptcha" class="reCaptcha">
    <div id="e_Captcha" class="g-recaptcha" data-sitekey="<?php echo SITE_KEY; ?>" data-callback="recaptchaCallbackEvent"></div>
</div>

我在我的 js 的顶部声明 widgetId

Recaptcha 有一个 onload 回调,一旦加载 recaptcha 就会 运行。将您的代码放在该回调函数中。

https://developers.google.com/recaptcha/docs/display

//call this function in your js
function onloadCallback() {
    $('.g-recaptcha').each(function(index, el) {
        widgetId = grecaptcha.render(el, {'sitekey' : 'My-SITE-KEY'});
    });
}

//load this script before your js is loading
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"></script>
//your html is absolutely fine.