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, built-in Captcha Ajax validation, 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 result 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 first result in the PreAjaxValidate event, and later in either AjaxValidationFailed or AjaxValidationPassed depending on whether the server responds that the typed-in Captcha code was correct or not. In case of Ajax asynchronous request errors, AjaxValidationError will be called.

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/traditional-api/bdc4-traditional-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 and botdetect-servlet.jar are in the classpath.


<%@page import="com.captcha.botdetect.web.servlet.Captcha"%> 
<%@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 
        Captcha captcha = Captcha.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 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  CaptchaId ' + this.Id + '\n  InstanceId ' + this.InstanceId); 

    // 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)); 

     // register handlers for the four steps of the BotDetect Ajax validation workflow 
    BotDetect.RegisterCustomHandler('PreAjaxValidate', function() { 
      log('PreAjaxValidate\n  ' + format(this.ValidationUrl + '&i=' + this.GetUserInputElement().value)); 

    BotDetect.RegisterCustomHandler('AjaxValidationFailed', function() { 

    BotDetect.RegisterCustomHandler('AjaxValidationPassed', function() { 

    BotDetect.RegisterCustomHandler('AjaxValidationError', function() { 

    BotDetect.RegisterCustomHandler('OnHelpLinkClick', function() { 
      this.FollowHelpLink = false; // abort help page opening 

    function startAsyncCaptchaValidation() { 
      var input = document.getElementById('captchaCode'); 
      if (input && 'text' == input.type) { 
        // call the BotDetect built-in client-side validation function 
        // this function must be called after the Captcha is displayed on the page, otherwise the 
        // client-side object won't be initialized 

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 CaptchaServlet used for BotDetect Captcha requests.

Please Note

BotDetect Java Captcha Library v4.0.Beta3.6 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.