All Products
Search
Document Center

Captcha:Use WebView to integrate CAPTCHA 2.0 into an Android application

Last Updated:Aug 14, 2024

As the development technology of hybrid applications becomes more sophisticated, you can integrate mobile HTML5-based CAPTCHA 2.0 into an Android application by using the WebView component to achieve anti-bot protection for the application. This topic describes how to integrate CAPTCHA 2.0 into an Android application.

Background information

Mobile HTML5-based CAPTCHA 2.0 offers the advantages of rapid iteration and strong compatibility. By integrating mobile HTML5-based CAPTCHA 2.0 into an application, you no longer need to worry about the compatibility issues that may be caused by various dependencies and references in the native application components. Thanks to the rapid iteration of mobile HTML5-based CAPTCHA 2.0, you can better protect your application against strong adversarial attacks.

Procedure

To integrate HTML5-based CAPTCHA 2.0 into an Android application, perform the following steps:

  1. Integrate CAPTCHA 2.0 into the HTML5 page client.

  2. Integrate a CAPTCHA 2.0 server SDK into the business server of the HTML5 page client, and then call the VerifyIntelligentCaptcha operation on the business server to initiate a verification request.

  3. Use the WebView component to load and deploy the business page on which you want to call CAPTCHA 2.0 on an Android application.

If you have questions during integration, submit a ticket to contact technical support.

Prerequisites

  • CAPTCHA 2.0 is activated, and a verification scenario whose Client Type is set to App(Webview+H5) is created. For more information, see the Step 2: Create a verification scenario section of the "Integration guide" topic.

  • An Android application of V7.0 or later is installed.

Step 1: Integrate CAPTCHA 2.0 into the HTML5 page client

  1. Integrate the client code provided by CAPTCHA 2.0 into the code of the HTML5 page client. For more information, see Integrate CAPTCHA 2.0 into a business client.

  2. Modify the client integration code based on the environment in which the business result verification is performed.

    • If the business result verification is performed on the Android application, you must modify the following code:

      1. Add the corresponding JavaScript function to the callback function for the business request to return the verification result to the custom testJsInterface operation. For more information about the testJsInterface operation, see Substep 5 and Substep 6 in the "Step 3: Load and deploy the HTML5 business page in the Android application" section of this topic. After the verification result is returned to the testJsInterface operation, you can perform different business operations on the Android application.

        // The callback function for the business request with CAPTCHA verification.
        async function captchaVerifyCallback(captchaVerifyParam) {
          // 1. Initiate a business request to the backend. Then, both the CAPTCHA verification result and the business result are returned.
          const result = await xxxx('http:// The URL of your business request', {
              captchaVerifyParam: captchaVerifyParam, // The CAPTCHA parameter.
              yourBizParam... // The business parameter.
          });
        
          // 2. Construct standard response parameters.
          const verifyResult = {
            captchaResult: result.captchaVerifyResult, // Required. Indicates whether the CAPTCHA verification is passed. The value is of the BOOLEAN type.
            bizResult: returns the business verification result, // Optional. Indicates whether the business verification is passed. The value is of the BOOLEAN type. If no business verification scenario is involved, the bizResult parameter is left empty.
          };
          // Return the verification result to the testJsInterface operation.
          window.testInterface && window.testInterface.getVerifyResult(JSON.stringify(verifyResult));
          return verifyResult;
        }
      2. Define the callback function for the business request verification result of the HTML5 page as an empty function. This operation migrates business operations from the HTML5 page to the Android application.

        // The callback function for the business request verification result.
        function onBizResultCallback(bizResult) {
          // Define the function as an empty function.
        }
    • If the business result verification is performed on the HTML5 page, you do not need to modify the code.

    • If the business result verification is performed on both the HTML5 page and the Android application, you must modify the following code. This enables the HTML5 page and Android application to use the same set of integration code but independent business result verification logic.

      1. Add the corresponding JavaScript function to the callback function for the business request. For more information, see Substep i in the "Step 1: Integrate CAPTCHA 2.0 into the HTML5 page client" section of this topic.

      2. Modify the callback function for the business request verification result of the HTML5 page to check whether the verification is performed on the HTML5 page. If the verification is performed on the HTML5 page, add the business logic of the HTML5 page.

        // The callback function for the business request verification result.
        function onBizResultCallback(bizResult) {
          // Check whether the business result verification is performed on the Android application. If the custom JavaScript function is not involved in the verification environment, the business result verification is performed on the HTML5 page.
          // You can also use a custom condition to distinguish between the two environments.
          if (!window.testInterface || !window.testInterface.getSlideData) {
              // The business logic of the HTML5 page.
          }
        }

Step 2: Integrate CAPTCHA 2.0 into the business server of the HTML5 page client

Integrate a CAPTCHA 2.0 server SDK into the business server of the HTML5 page client, and then call the VerifyIntelligentCaptcha operation to initiate a verification request. For more information, see Integrate CAPTCHA 2.0 into a business server.

Important

After you complete server integration, make sure that CAPTCHA 2.0 is integrated into the business client and business server. For more information, see the Step 3: Integrate CAPTCHA 2.0 section of the "Integration guide" topic.

Step 3: Load and deploy the HTML5 business page on the Android application

  1. In the Activity.java file of your Android application project, import the dependency library of the WebView component.

    import android.webkit.WebView;
    import android.webkit.WebSettings;
    import android.webkit.WebViewClient;
    import android.webkit.WebChromeClient;
    // Or
    // import android.webkit.*;
  2. In the AndroidManifest.xml configuration file, specify the permissions on HTML5 page loading.

    Note

    If other HTTP resources are called, you must add the corresponding configurations.

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    <application
      ...
      android:usesCleartextTraffic="true"
      ...
      >
  3. In the activity_main.xml layout file, add the WebView component.

    <WebView android:id="@+id/webview"
                android:layout_height="match_parent"
                android:layout_width="match_parent" />
  4. In the MainActivity.java file, load the HTML5 business page.

    public class MainActivity extends AppCompatActivity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            initView();
        }
        private void initView() {
            // The page layout.
            WebView webview = findViewById(R.id.webview);
            // The WebView settings.
            WebSettings webSettings = webview.getSettings();
            // Optional. Enable Chrome debugging.
            WebView.setWebContentsDebuggingEnabled(true);
            // Enable adaptive scaling for the screen.
            webSettings.setUseWideViewPort(true);
            webSettings.setLoadWithOverviewMode(true);
            // The cache mode. To ensure that you can obtain the latest CAPTCHA 2.0 service to defend against attacks, we recommend that you disable cache loading.
            webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
            // Enable the WebView component to load JavaScript.
            webSettings.setJavaScriptEnabled(true);
            webSettings.setDomStorageEnabled(true);
            
            // Enable the system to use the WebView component to load the business page instead of using the default browser.
            webview.setWebViewClient(new WebViewClient(){
                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) { 
                    view.loadUrl(url);
                    return true;
                }
            });
            // Load the business page.
            webview.loadUrl("http://x.x.x.x/demo/");
        }
    }
  5. In the MainActivity.java file, add the custom testJsInterface operation and define getVerifyResult as the method to obtain the verification result.

    import android.webkit.JavascriptInterface;
    
    public class testJsInterface {
        @JavascriptInterface
        public void getVerifyResult(String verifyResult) {
            // After the verification result is returned, you can perform different business operations.
            System.out.println(verifyResult);
        }
    }
  6. In the initView() method of the MainActivity.java file, associate the testJsInterface operation with the JavaScript function.

    // Enable the JavaScript function to call the testJsInterface operation.
    testWebview.addJavascriptInterface(new testJsInterface(), "testInterface");

After you complete the preceding steps, CAPTCHA 2.0 is integrated into your Android application. You can use CAPTCHA 2.0 on your Android application to check the verification effect. If CAPTCHA 2.0 works as expected, the integration is successful.