显式呈现 ReCaptcha - Onload 函数未触发

Explicitly Rendering ReCaptcha - Onload Function Not Firing

从文档中我了解到,为了更改 recaptcha 的语言,我必须明确地呈现它。

然而,问题是它并没有真正出现,而且 onload 甚至都没有被调用。
当我尝试自动渲染它时,它确实有效。

代码如下:
在 HTML 头部:(我也试过把它放在 body 标签的末尾)

<script src="https://www.google.com/recaptcha/api.js?onload=recaptchaCallback&render=explicit&hl=iw" async defer></script>

在HTML形式中:

<div id="recaptcha"></div>

Javascript:

var recaptchaCallback = function() {
  console.log('recaptcha is ready'); // not showing
  grecaptcha.render("recaptcha", {
    sitekey: 'My Site Key',
    callback: function() {
      console.log('recaptcha callback');
    }
  });
}

我刚刚复制了您的代码,使用了我自己的站点密钥,并且有效。

我使用的代码是:

<html>
  <body>
    <p>ReCaptcha Test</p>

    <div id="recaptcha"></div>

    <script src="https://www.google.com/recaptcha/api.js?onload=recaptchaCallback&render=explicit&hl=iw" async defer></script>

    <script type="text/javascript">
      var recaptchaCallback = function () {
        console.log('recaptcha is ready'); // showing
        grecaptcha.render("recaptcha", {
            sitekey: 'SITE_KEY',
            callback: function () {
                console.log('recaptcha callback');
            }
        });
      }
    </script>

  </body>
</html>

仔细检查您的代码,因为一个字符的拼写错误可能会导致程序无法运行。

确保你的 onload 方法定义在 recaptcha 脚本之前。否则,您将遇到竞争条件,recaptcha 脚本可能会在定义之前尝试调用您的方法(尤其是在缓存 recaptcha 脚本的情况下)。

来自 onload 的文档 https://developers.google.com/recaptcha/docs/display

Note: your onload callback function must be defined before the reCAPTCHA API loads. To ensure there are no race conditions:

  • order your scripts with the callback first, and then reCAPTCHA
  • use the async and defer parameters in the script tags

例如:

<div id="recaptcha"></div>


<script type="text/javascript">
  var recaptchaCallback = function () {
    console.log('recaptcha is ready'); // not showing
    grecaptcha.render("recaptcha", {
        sitekey: 'SITE_KEY',
        callback: function () {
            console.log('recaptcha callback');
        }
    });
  }
</script>

<script src="https://www.google.com/recaptcha/api.js?onload=recaptchaCallback&render=explicit&hl=iw" async defer></script>

HTML

<div id="captcha"></div>
<script src='https://www.google.com/recaptcha/api.js?onload=recaptchaReadycallback&render=explicit' async defer'></script>

JavaScript

// Render captcha and set call back function on api.js load finish
function recaptchaReadycallback(){
 grecaptcha.render('captcha', {
    'callback' : recaptchaCheckedCallback,
    'expired-callback': recaptchaExpiredCallback,
    'sitekey': 'YOUR-SITE-KEY'

  });
}

// On expiry do stuff. E.g. show error
function recaptchaExpiredCallback(){
   grecaptcha.reset();
   // Show 'check the bloody box' error
};

// On not a robot confirmation do stuff. E.g. hide error
function recaptchaCheckedCallback(){
   // Hide 'check the bloody box' error
}

我的问题是我没有意识到第二个回调仅在提交表单时触发 - 而第一个回调在页面加载时执行。