DEV Community

Huzaifa Rasheed
Huzaifa Rasheed

Posted on

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 😉.

Top comments (2)

Collapse
 
jfinkel profile image
jfinkel

Thanks, but may I suggest that you have obfuscated the example by 1) adding unnecessary CSS code and 2) by not simply showing the code so that we do not have to "Show page source."

But I appreciate your effort, even though it is hard for me to use your example as a template.

Collapse
 
blessed_obeng_82490ce2413 profile image
Blessed Obeng

recaptcha html