Google reCAPTCHA in HTML and JavaScript

This post is using two HTML pages that have only JavaScript enabled. Feel free to replace some of the code with JQuery if you are loading those scripts. Otherwise, you can implement Google reCAPTCHA in HTML and JavaScript.

Google reCAPTCHA
Google reCAPTCHA

Google has a client side implementation for their reCAPTCHA on your web pages. Their documentation is great at explaining what it is, but it lacks in specific examples for how to implement in different environments. This causes confusion with some developers when they paste the two lines of code in their web page, but they are still able to submit the page, even when they don’t fill in the CAPTCHA.

I’ve noticed during testing that it may be possible to get through the CAPTCHA the first time. On subsequent requests, probably based on IP address, it creates a popup that you have to select photos from. That should stop most bot engines. Just mentioning so you don’t think there’s a problem if you still occasionally get a form submit that looks like it could be a bot.

The getting started section of the Google Developer’s Guide is fine for getting started, but I’ll still cover it here, as I strongly dislike blog posts that only show 80% of the solution.

First thing you need is the actual URL that your going to deploy the application on. So if you haven’t registered one yet, you should do that now. I don’t know how Google handles it when two people try to register the same domain with reCAPTCHA, but I would assume that it would be questioned at some level. Maybe I’ll do an investigation in the future when I’m bored. I just feel that I don’t want to setup a domain under my Google account and then find out later someone else registered the domain and I’ve made a potential problem for them.

Okay, so let’s get started:

  1. Register your domain, as previously mentioned.
  2. Sign up for your reCAPTCHA at Google.
    1. Save your site and private/secret key somewhere in your source control
  3. Place the script call on your page, preferably in the header, but it doesn’t have to be if you use frames etc.
<script src="https://www.google.com/recaptcha/api.js" async defer> </script>

4. WITHIN THE FORM TAGS of your page, place the widget. This is the “Implicit” method of displaying the reCAPTCHA widget.

<div class="g-recaptcha"></div>

5. Create a javascript function that you can call to validate the CAPTCHA response from Google.

function VerifyCAPTCHA() {
	var response = grecaptcha.getResponse();

    alert(response);

    if(response.length == 0)
    {
        // reCaptcha not verified
        var textbox = document.getElementById('errortext');
        textbox.value = 'reCAPTCHA failed you BOT!';
        return false;
    }
    else
    {
		window.location.assign('http://www.yourdomain.com/MyResultsPage.html');
    }
};
6. Create the button that will validate your CAPTCHA on submit.
        <div>
            <input type="button" name="submitButton" value="Show Results!" onclick="javascript: VerifyCAPTCHA();" />
        </div>

A few things to note:
1) Notice that the button is of type “button”, not “submit”. This is because we’re going to depend on our VerifyCAPTCHA() function to redirect us on success.
2) You don’t need your Private/Secret key for this type of implementation.

Now when you run your page with the CAPTCHA on it, it will have to pass this response test before redirecting. On the page you’re redirecting to, you should have some code to verify that the referrer is your CAPTCHA page. This is because any BOT can look for window.location statements and follow them on their own, so you’ll want to stop deep linking in it’s tracks.

The version 1.0 of reCAPTCHA used to allow you to debug using localhost without issue. The new version doesn’t. I can only assume that this was done for security reasons.

I hope that this post helps you to get up and running quickly with Google’s reCAPTCHA without the two or three hours of frustration that I had.

Author: Jack Yasgar

Jack Yasgar has been developing software for various industries for two decades. Currently, he utilizes C#, JQuery, JavaScript, SQL Server with stored procedures and/or Entity Framework to produce MVC responsive web sites that converse to a service layer utilizing RESTful API in Web API 2.0 or Microsoft WCF web services. The infrastructure can be internal, shared or reside in Azure. Jack has designed dozens of relational databases that use the proper primary keys and foreign keys to allow for data integrity moving forward. While working in a Scrum/Agile environment, he is a firm believer that quality software comes from quality planning. Without getting caught up in analysis paralysis, it is still possible to achieve a level of design that allows an agile team to move forward quickly while keeping re-work to a minimum. Jack believes, “The key to long term software success is adhering to the SOLID design principles. Software written quickly, using wizards and other methods can impress the business sponsor / product owner for a short period of time. Once the honeymoon is over, the product owner will stay enamored when the team can implement changes quickly and fix bugs in minutes, not hours or days.” Jack has become certified by the Object Management Group as OCUP II (OMG Certified UML Professional) in addition to his certification as a Microsoft Certified Professional. The use of the Unified Modeling Language (UML) provides a visual guide to Use Cases and Activities that can guide the product owner in designing software that meets the end user needs. The software development teams then use the same drawings to create their Unit Tests to make sure that the software meets all those needs. The QA testing team can use the UML drawings as a guide to produce test cases. Once the software is in production, the UML drawings become a reference for business users and support staff to know what decisions are happening behind the scenes to guide their support efforts.

2 thoughts on “Google reCAPTCHA in HTML and JavaScript”

    1. Hi Aaron,

      When you’re using Javascript, you don’t use the private key. Yes, this is just checking that google either responds or not, it’s not validating all of your site settings. The reason for this is because all of your code is in Javascript, which anyone can right click and view source to see your private key, which wouldn’t be very private.

Leave a Reply

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