Adding Google's reCAPTCHA To Your Form
Recently I was tasked with adding Google’s reCAPTCHA to a couple of forms on one of our static sites. For what it’s worth, our site is running on Astro. Just wanted to add that in. Anyway I have no experience with reCAPTCHA so I was thankful that a link to their docs was included in the issue.
You have some options when using reCAPTCHA. Versions 3 and 2. I opted for reCAPTCHA v2 Invisible. This prevents users from selecting fire hydrents or buses or whatever silly things one needs to click to prove they are a centient carbon based life form.
Adding Your Domain
One of the first steps is adding your domain to your Admin Console in Google. In the console you will need to specify the version you want to use.
This can all be tested locally too. All you need to do is add localhost
to the list of domains. Google reccomends using a seperate key for your local environment. This isn’t necesarry but Google says it’s a good idea.
The Code
Here’s the code inside our form component:
<script type="text/javascript">
var onSubmit = () => {
document.getElementById("contact-form").submit()
};
var onloadCallback = () => {
grecaptcha.render('js-form-submit', {
'sitekey' : 'your_site_key',
'callback' : onSubmit
});
};
</script>
<form
method="post"
id="contact-form"
>
{/* Lots of inputs */}
<div id="post-registration-form"></div>
<input
type="submit"
id="js-form-submit"
value="Submit"
/>
</form>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"
async defer>
</script>
You could simplify this even more. According to google, the simplest way is to bind reCAPTCHA to a button on the form. For this approach you will need to add:
class="g-recaptcha"
data-sitekey="your_site_key"
data-callback="onSubmit"
to your button or input that submits your form. Inside the onSubmit()
function submit your form.
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<script>
var onSubmit = () => {
document.getElementById("contact-form").submit();
}
</script>
<form
method="post"
id="contact-form"
>
{/* Lots of inputs */}
<input
class="g-recaptcha"
data-sitekey="your_site_key"
data-callback="onSubmit"
type="submit"
value="Submit"
/>
</form>
That’s it really. The docs on reCAPTCHA are quite good. Check them out to find the option that works best for you.