Add Google reCAPTCHA v2 to plain HTML

rhuzaifa

Huzaifa Rasheed

Posted on February 12, 2022

Add Google reCAPTCHA v2 to plain HTML

What is it?

A CAPTCHA is a test that helps to tell the difference between a bot and a human.

The reCAPTCHA is Google's implemenation of a CAPTCHA. Its very easy to integrate, without any third party libraries.

What's The Purpose?

A reCAPTCHA can keep malicious software/bots from engaging in abusive activities on your website while allowing legitimate users access to your site.

How to Integrate?

We will be using the v2 version.

1. Create a site key
You can create a site key from Google reCAPTCHA Admin Page.

You also will need to add a site domain, where you would deploy the site. For testing you can add localhost and use the loopback address (127.0.0.1) or use a key from reCAPTCHA automated tests guide. One of those keys is

6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI
Enter fullscreen mode Exit fullscreen mode

which we will use in our example.

2. Add Widget to Markup
The only thing we will need to add to our HTML is

<div
  class="g-recaptcha"
  data-sitekey="6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI"
>
</div>
Enter fullscreen mode Exit fullscreen mode

this can be added to a form or used without one, depending on the use case. Source

We will also need to add a cdn link to the head tag.

<script src="https://www.google.com/recaptcha/api.js" async defer>
</script>
Enter fullscreen mode Exit fullscreen mode

We can listen to callbacks from the widget and register our own handlers.

<div
  class="g-recaptcha"
  data-sitekey="6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI"
  data-callback="onRecaptchaSuccess"
  data-expired-callback="onRecaptchaResponseExpiry"
  data-error-callback="onRecaptchaError"
>
</div>
Enter fullscreen mode Exit fullscreen mode

these callbacks can be used to validate or invalidate our form or whatever we want to do.

I made a simple form that submits successfully when the reCAPTCHA validates successfully, its here. I also added some basic styling to have a decent look and feel.

Hope this helps you in your Projects. Thanks for reading ๐Ÿ˜‰.

๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ
rhuzaifa
Huzaifa Rasheed

Posted on February 12, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

ยฉ TheLazy.dev

About