显式渲染ReCaptcha - Onload函数未触发

问题描述 投票:12回答:4

从我理解的文档中,为了改变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');
    }
  });
}
javascript html5 recaptcha
4个回答
10
投票

我刚刚复制了你的代码,使用了我自己的Site Key,它确实有效。

我使用的代码是:

<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>

仔细检查您的代码,因为只有一个字符错误可以阻止工作。


17
投票

确保在recaptcha脚本之前定义了onload方法。否则,您将遇到竞争条件,其中recaptcha脚本可能会在定义之前尝试调用您的方法(特别是如果缓存了重新访问脚本)。

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

注意:必须在加载reCAPTCHA API之前定义onload回调函数。确保没有竞争条件:

  • 首先使用回调对脚本进行排序,然后再使用reCAPTCHA
  • 在脚本标记中使用async和defer参数

例如:

<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>

0
投票

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. i.e. show error 
       function recaptchaExpiredCallback(){
          grecaptcha.reset();
          //show 'check the bloody box' error
       };

       //on not a robot confirmation do stuff. i.e. hide error
       function recaptchaCheckedCallback(){
          //hide 'check the bloody box' error
       }

0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.