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
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>
Sometimes the application loads several times the script 'https://www.google.com/recaptcha/api.js
after refresh, make sure your application doesn't have multiple <script async="" defer="" src="https://www.google.com/recaptcha/api.js"></script>
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>
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. :)
I have solved this by ordering the script in below manner
<div id="review_recaptcha"></div>
<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>
I know this is an old question but maybe this will help someone. The reason I was getting this 'Uncaught ReferenceError: grecaptcha is not defined' error was because I couldn't reach the dependency js file (recaptcha_en.js) which is hosted on www.gstatic.com. Once I solved that issue, it worked for me.