BotDetect CAPTCHA Options: Client-Side Workflow Settings Code Example

The Java Captcha options: Client-Side workflow settings code example shows how to use custom BotDetect client-side events to execute user-defined JavaScript code at various stages of the Captcha challenge workflow.

First Time Here?

Check the BotDetect Developer Crash Course for key integration steps.

Client-side Captcha object initialization, Captcha image reloading, Captcha sound playback, and Captcha help link clicks all have a number of related client-side "events" and hooks where user-defined client-side callbacks can be injected.

User code can be associated with Captcha workflow events using the BotDetect.registerCustomHandler() function, as shown in the example JavaScript code.

Loading the form will initialize the client-side Captcha object (created by the BotDetect.init() JavaScript call included in Captcha markup), and result in the postInit event.

Clicking the Captcha sound icon will reuslt in the prePlaySound event before the audio elements are added to the page DOM. There is no postPlaySound event since not all browsers allow user callbacks when browser sound playing finishes.

Clicking the Captcha reload icon will result in preReloadImage and postReloadImage events, executed before and after the Http request loading the new Captcha image from the server.

Clicking the Captcha image (i.e. the included Captcha help link) will result in the onHelpLinkClick event.

Typing in a Captcha code and clicking the Validate button will perform client-side captcha validation using JQuery Ajax.

Download the BotDetect Java CAPTCHA Library and run this example

Example Location

The Java Captcha options: Client-Side workflow settings code example is included in the examples/simple-api/bdc4-simple-api-captcha-clientside-workflow-settings-example.war file of the download package. Deploying (unpacking) the file will create a standard JSP directory tree.

Running Example

This example's war file (in BotDetect download package) already embeds all dependencies.

In case you are making this example from scratch in your IDE, you need to ensure botdetect.jar, botdetect-servlet.jar, and hsqldb.jar are in the classpath.


<%@page import="com.captcha.botdetect.web.servlet.SimpleCaptcha"%>
<%@page trimDirectiveWhitespaces="true"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>BotDetect Java CAPTCHA Options: Client-Side Workflow Settings Code Example</title>
  <link type="text/css" rel="stylesheet" href="stylesheet.css" />
  <form method="post" action="" class="column" id="form1">

    <h1>BotDetect Java CAPTCHA Options: <br /> Client-Side Workflow Settings Code Example</h1>

      <legend>Java CAPTCHA validation</legend>
      <label for="captchaCode">Retype the characters from the picture:</label>

        // Adding BotDetect Captcha to the page
        SimpleCaptcha captcha = SimpleCaptcha.load(request, "clientSideEventsCaptcha");
        String captchaHtml = captcha.getHtml();

      <div class="validationDiv">
        <input name="captchaCode" type="text" id="captchaCode" />
        <input type="submit" name="ValidateCaptchaButton" id="validateCaptchaButton" value="Validate" onclick="startAsyncCaptchaValidation(); return false;" />

          // when the form is submitted
          if ("POST".equalsIgnoreCase(request.getMethod())) {
            // validate the Captcha to check we're not dealing with a bot
            boolean isHuman = captcha.validate(request.getParameter("captchaCode"));
            if (isHuman) {
              // Captcha validation passed, perform protected action
              out.print("<span class=\"correct\">Correct code</span>");
            } else {
              // Captcha validation failed, show error message
              out.print("<span class=\"incorrect\">Incorrect code</span>");
    <h4>Custom BotDetect Client-Side Events Debug Log</h4>
    <div id="output"></div>
  <script src="js/jquery-1.7.2.min.js"></script>        
  <script type="text/javascript">
    function log(text) {
      var output = document.getElementById('output');
      var line = document.createElement('pre');
      line.innerHTML = timestamp() + ' ' + text;
      output.insertBefore(line, output.firstChild);

    function timestamp() {
      return new Date().toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1");

    function format(url) {
      return url.replace(/^.*?\?/g, '').replace(/&/g, '\n  &');

    BotDetect.registerCustomHandler('postInit', function() { 
      log('postInit \n  captchaStylename ' + this.captchaStyleName + '\n  captchaId ' + this.captchaId); 

    // custom javascript handler executed before Captcha sounds are played
    BotDetect.registerCustomHandler('prePlaySound', function() { 

    // custom javascript handler executed before Captcha images are reloaded
    BotDetect.registerCustomHandler('preReloadImage', function() { 
      log('preReloadImage\n  ' + format(this.image.src) + '\n  autoReload: ' + this.autoReloading); 

    // custom javascript handler executed after Captcha images are reloaded
    BotDetect.registerCustomHandler('postReloadImage', function() { 
      log('postReloadImage\n  ' + format(this.image.src)); 


    BotDetect.registerCustomHandler('onHelpLinkClick', function() { 
      this.followHelpLink = false; // abort help page opening

    function startAsyncCaptchaValidation() {
      // BotDetect CAPTCHA object
      // this function must be called after the Captcha is displayed on the page, otherwise the
      // client-side object won't be initialized
      var captcha = BotDetect.getInstanceByStyleName('clientSideEventsCaptcha');
      if (captcha === null) {
      // BotDetect client-side validation url
      var validationUrl = captcha.validationUrl;
      // captcha code
      var captchaCode = $('#captchaCode').val();
        method: "GET",
        url: validationUrl,
        data: {
          i: captchaCode
        beforeSend: function() {
          log('pre ajax validate\n  ' + format(validationUrl + '&i=' + captchaCode));
        success: function(response) {
          if (response) {
            log('ajax validation passed');
          } else {
            log('ajax validation failed');

In the form source, we follow the standard procedure for adding Captcha protection to a JSP form.

The script fragment below the form shows a very simple example of using the BotDetect client-side API to customize Captcha behavior.


<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns=""
    <servlet-name>BotDetect Captcha</servlet-name>
    <servlet-name>BotDetect Captcha</servlet-name>

In WEB-INF/web.xml file we register SimpleCaptchaServlet used for BotDetect Captcha requests.

Please Note

BotDetect Java Captcha Library v4.0.Beta3.5 is an in-progress port of BotDetect 4 Captcha, and we need you to guide our efforts towards a polished product. Please let us know if you encounter any bugs, implementation issues, or a usage scenario you would like to discuss.

Current BotDetect Versions