Back to Blog
Attack Prevention

How to Use hCaptcha with Android Apps

June 21, 2019

Share
Good news! It is quite simple to integrate hCaptcha with your native Android app today.

(Note: if you are using Flutter, please see our hCaptcha Flutter guide.)

2021 Update
The article below is now outdated: please use our
native Android SDK.

Simply create an HTML file with a hCaptcha form (see hCaptcha docs) and host that on your web site. Then load the URL in a WebView and create a bridge between Java and Javascript (addJavascriptInterface).

Android Activity:

WebView mWebView = (WebView) findViewById(R.id.webview); mWebView.getSettings().setJavaScriptEnabled(true); mWebView.getSettings().setBuiltInZoomControls(false); mWebView.loadUrl("https://your.server/hcaptcha_form.html"); mWebView.addJavascriptInterface(new BridgeWebViewClass(this), "BridgeWebViewClass");

Note: if you are an hCaptcha Enterprise customer, you can also embed the HTML file directly into your mobile app.

mWebView.loadUrl("https://your.server/hcaptcha_form.html");

in your Activity instead becomes:

mWebView.loadUrl("file:///android_asset/myFolder/hcaptcha_form.html");

Contact the integration engineering team for further guidance to enable this.

Bridge Class:

public class BridgeWebViewClass { @JavascriptInterface public void hCaptchaCallbackInAndroid(String h_response){ log.d("hCaptcha", "token" + h_response); } }

Now from your HTML file you can run the Bridge Class as a Javascript function:

<div class="h-captcha" data-sitekey="YOUR_CAPTCHA_SITE_KEY" data-callback="captchaResponse"></div> <script type="text/javascript"> function captchaResponse(token){ BridgeWebViewClass.hCaptchaCallbackInAndroid(token); } </script>

Finally, pass the response token returned above to your backend server, and have it call siteverify to check that the token is valid.

Let us if you have any questions!

Credit: this method was inspired by a similar StackOverflow answer.

Subscribe to our newsletter

Stay up to date on the latest trends in cyber security. No spam, promise.
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.

Back to blog