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
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>
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>
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>
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. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With