Friday, October 15, 2010

Adding reCAPTCHA with JavaScript

In some dynamic interfaces, you may not want to load reCAPTCHA with the initial page loaded. In others you can’t because it would expire by the time the user uses that piece of the UI.

In the above scenarios you can add reCAPTCHA just when you need it.

First include the recaptcha script:

<script type="text/javascript" src='http://www.google.com/recaptcha/api/js/recaptcha_ajax.js'></script>
If the page is served over https make sure to use that in the above url. Alternatively do it dynamically, like in asp.net MVC you can do:
<script type="text/javascript" src='<%= Request.Url.Scheme + 
"://www.google.com/recaptcha/api/js/recaptcha_ajax.js" %>'></script>
Add an empty div where you’ll want the reCAPTCHA to appear in the HTML.
In the corresponding JavaScript action, do:
Recaptcha.create(theRecaptchaPublicKey, targetDiv);
If you are using jQuery, one way is to retrieve it based on a css class like:
$('#someContainer .captcha').each(function () {
Recaptcha.create(theRecaptchaPublicKey, this);
});

No comments:

Post a Comment

Post a Comment