Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught ReferenceError: grecaptcha is not defined

I am using recaptcha v2

I am getting the following error occasionally (sometimes i don't get error and sometimes i do get it)

Uncaught ReferenceError: grecaptcha is not defined

It seems because of the internal http request. that takes some time to get another js recaptcha__en.js. Meanwhile actual rendering code of grecaptcha executes.

So what is the standard solution to avoid this issue.?

PS : of course i am looking for some solution other than setTimeout

like image 961
codeofnode Avatar asked Apr 23 '15 11:04

codeofnode


4 Answers

Recaptcha has a onload callback that will run once recaptcha is loaded. Place your code inside that callback function.

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

<script>
    function onloadCallback() {
        /* Place your recaptcha rendering code here */
    }
</script>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"></script>
like image 154
Vigneswaran Marimuthu Avatar answered Nov 13 '22 18:11

Vigneswaran Marimuthu


I have solved this by ordering the script in below manner

HTML

<div id="review_recaptcha"></div>

jQuery

<script type="text/javascript">
      var review_recaptcha_widget;
      var onloadCallback = function() {
        if($('#review_recaptcha').length) {
            review_recaptcha_widget = grecaptcha.render('review_recaptcha', {
              'sitekey' : '<?php echo $site_key?>'
            });
        }
      };      
</script>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer></script>
like image 6
diEcho Avatar answered Nov 13 '22 18:11

diEcho


My Problem got resolved by doing following changes in the script code (:

i.e from internal path

<script src='static/js/recaptcha/api.js'></script>

to external google path i.e

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

like image 3
Walk Avatar answered Nov 13 '22 20:11

Walk


It works on landing page and also in bootstrap 4 popup form:

<script src="https://www.google.com/recaptcha/api.js?render=ADD-YOUR-RECAPTCHA-SITE-KEY-HERE"></script>
<script>
var interval = setInterval(function(){
  if(window.grecaptcha){
        grecaptcha.ready(function() {
            grecaptcha.execute('ADD-YOUR-RECAPTCHA-SITE-KEY-HERE', {action: 'homepage'}).then(function(token) {
              $('#i-recaptcha').prepend('<input type="hidden" name="g-recaptcha-response" value="' + token + '">');
            });
        });
    clearInterval(interval);
  }
}, 100);
</script>

Thanks for asking this question. :)

like image 3
Kamlesh Avatar answered Nov 13 '22 19:11

Kamlesh