Categories
Coding Websites

Applying callback to grecaptcha

We were having some troubles with some users rushing to click the submit button on a form immediately after clicking the good ‘ole “I’m not a robot” checkbox, instead of waiting nicely for the captcha to verify. By the way, that is TOTALLY what a robot would do, so it’s probably good that it fails the verification.

But to get the submit button to only enable after the checkbox turns green, you need to provide a “callback” routine for the grecaptcha. And, you can also provide a “expired-callback” routine for if the captcha box sits around too long after a check and then turns red. Note that you need to put the defined callbacks without quotes.

Also to add some complexity, we had two separate captchas in our page, so we had to define two of them. Some people have reported troubles doing so, but our final solution worked.

We had a problem where the callback routines were not being called, but everything else was working — it turns out we have the callback functions defined AFTER the render, and moving them before that section made everything work. So, the final layout:

<script src=”https://www.google.com/recaptcha/api.js?onload=myCaptInit&render=explicit” async defer></script>
<script>
var myCaptInit = function() {
var buton11 = function() {
$(“#mainsubmit”).removeAttr(“disabled”);
};
var butoff11 = function() {
$(“#mainsubmit”).attr(“disabled”, “disabled”);
};
grecaptcha.render(‘recaptcha11’, {
‘sitekey’: ‘xxxx’,
‘callback’: buton11,
‘expired-callback’: butoff11,
‘size’: ‘compact’
});
grecaptcha.render(‘recaptcha10’, {
‘sitekey’ : ‘xxxx’,
‘size’ : ‘compact’
});
};
</script>

Leave a Reply

Your email address will not be published. Required fields are marked *