> This page is for Applications Protection.

> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.humansecurity.com/llms.txt.

# Ionic Integration

> **Note**
>
> This guide is relevant for the current Mobile SDK. While we highly recommend using the latest version, if you are using a legacy integration, refer to the [iOS](/applications/ios-how-to-integrate-the-sdk-in-your-application-v3) or [Android](/applications/android-how-to-integrate-the-sdk-in-your-application-v3) documentation.

You can integrate the SDK into an [Ionic](https://ionicframework.com/) project. There is no HUMAN Ionic package. Call the native SDK from JavaScript through a Capacitor plugin.

## Prerequisites

If the app loads a HUMAN-protected site in a Capacitor WebView, set `hybridAppPolicy.webRootDomains` and `hybridAppPolicy.supportExternalWebViews = true` in native start. There is no wrapper-level default. Instead, the flag is set manually. See [WebView container support](/applications/sdk/v5/webview-container-support) for more information.

## Start the SDK

When starting the SDK, keep the following in mind:

1. **Start the SDK as soon as possible** on the **main thread**. We recommend doing so in the `Application`'s `onCreate` function on Android or the `AppDelegate`'s `didFinishLaunchingWithOptions` function on iOS. If your app sends a URL request to your server before the SDK starts, the request will not include the SDK's HTTP headers. As a result:
   * The

     Enforcer

     may block the request, and
   * The SDK will not be able to present a challenge to the user
2. Create a `HumanManager` that handles calls from Ionic.

Below are example implementations for Android and iOS:

> **Note**
>
> Don't forget to replace `<APP_ID>` with your actual **Application ID**.

#### Android

**`Java (MainApplication.kt)`**

```java title="Java (MainApplication.kt)"
import android.app.Application;

public class MainApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        HumanManager.startHumanSDK(this);
    }
}
```

**`Java (HumanManager.kt)`**

```java title="Java (HumanManager.kt)"
import android.app.Application;
import com.getcapacitor.JSObject;
import com.getcapacitor.Plugin;
import com.getcapacitor.PluginCall;
import com.getcapacitor.PluginMethod;
import com.getcapacitor.annotation.CapacitorPlugin;
import com.humansecurity.mobile_sdk.HumanSecurity;
import com.humansecurity.mobile_sdk.main.policy.HSPolicy;
import com.humansecurity.mobile_sdk.main.policy.HSAutomaticInterceptorType;
import com.humansecurity.mobile_sdk.main.HSBotDefenderChallengeResult;
import java.util.HashMap;
import android.util.Log;

@CapacitorPlugin(name = "Human")
public class HumanManager extends Plugin {

    String strSolved = "solved";
    String strCancelled = "cancelled";
    String strFalse = "false";
    String strValue = "value";

    static void startHumanSDK(Application application) {
        HSPolicy policy = new HSPolicy();
        policy.getAutomaticInterceptorPolicy().setInterceptorType(HSAutomaticInterceptorType.NONE);
        try {
            HumanSecurity.INSTANCE.start(application, "<APP_ID>", policy);
        }
        catch (Exception exception) {
            Log.e("HumanManager","Exception: " + exception.getMessage());
        }
    }

    @PluginMethod()
    public void getHttpHeaders(PluginCall call) {
        HashMap headers = HumanSecurity.INSTANCE.getBD().headersForURLRequest("<APP_ID>");
        JSObject ret = new JSObject();
        for (Object key : headers.keySet()) {
            ret.put((String)key, headers.get(key));
        }
        call.resolve(ret);
    }

    @PluginMethod()
    public void handleResponse(PluginCall call) {
        String response = call.getString(strValue);
        JSObject ret = new JSObject();
        boolean handled = HumanSecurity.INSTANCE.getBD().handleBlockResponse(response, null, result -> {
            ret.put(strValue, result == HSBotDefenderChallengeResult.SOLVED ? strSolved : strCancelled);
            call.resolve(ret);
            return null;
        });
        if (!handled) {
            ret.put(strValue, strFalse);
            call.resolve(ret);
        }
    }
}
```

**`Java (MainActivity.java)`**

```java title="Java (MainActivity.java)"
import android.os.Bundle;
import com.getcapacitor.BridgeActivity;

public class MainActivity extends BridgeActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        registerPlugin(HumanManager.class);
        super.onCreate(savedInstanceState);
    }
}
```

#### iOS

**`Swift (AppDelegate.swift)`**

```swift title="Swift (AppDelegate.swift)"
import UIKit
import Capacitor

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        HumanManagerPlugin.shared.start()
        return true
    }

    func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
        return ApplicationDelegateProxy.shared.application(app, open: url, options: options)
    }

    func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
        return ApplicationDelegateProxy.shared.application(application, continue: userActivity, restorationHandler: restorationHandler)
    }
}
```

**`Swift (HumanManager.swift)`**

```swift title="Swift (HumanManager.swift)"
import Foundation
import Capacitor
import HUMAN

@objc(HumanManagerPlugin)
class HumanManagerPlugin: CAPPlugin {

    let strSolved = "solved"
    let strCancelled = "cancelled"
    let strFalse = "false"
    let strValue = "value"

    static let shared = HumanManagerPlugin()

    func start() {
        do {
            let policy = HSPolicy()
            policy.automaticInterceptorPolicy.interceptorType = .none
            try HumanSecurity.start(appId: "<APP_ID>", policy: policy)
        }
        catch {
            print("Error: \(error)")
        }
    }

    @objc func getHttpHeaders(_ call: CAPPluginCall) {
        call.resolve(HumanSecurity.BD.headersForURLRequest(forAppId: "<APP_ID>"))
    }

    @objc func handleResponse(_ call: CAPPluginCall) {
        let response = call.getString(strValue) ?? ""
        guard let data = response.data(using: .utf8) else {
            call.resolve([strValue: strFalse])
            return
        }
        let handled = HumanSecurity.BD.handleBlockResponse(data: data, url: nil) { challengeResult in
            call.resolve([self.strValue: challengeResult == .solved ? self.strSolved : self.strCancelled])
        }
        if !handled {
            call.resolve([strValue: strFalse])
        }
    }
}
```

**`Objective-C (HumanManagerPlugin.m)`**

```c title="Objective-C (HumanManagerPlugin.m)"
#import <Foundation/Foundation.h>
#import <Capacitor/Capacitor.h>

CAP_PLUGIN(HumanManagerPlugin, "HUMAN",
    CAP_PLUGIN_METHOD(getHttpHeaders, CAPPluginReturnPromise);
    CAP_PLUGIN_METHOD(handleResponse, CAPPluginReturnPromise);
)
```

In particular, note the following:

1. **Initialization:** We start the SDK as early as possible on the main thread.
2. **Policy configuration:** We create an `HSPolicy` instance and set the `HSAutomaticInterceptorPolicy/interceptorType` property to `HSAutomaticInterceptorType/none`. That disables **Automatic Interception**, which lets the SDK manipulate URL requests and handle their responses, but isn't supported in Ionic.
3. **Starting the SDK:** We call `HumanSecurity/start(appId:policy:)` with the following parameters:
   * The `Application` instance (Android only)
   * Your

     Application ID

     . If you have multiple IDs, see our [guide](/applications/sdk/v5/getting-started#handle-multiple-application-ids) on how to handle them.
   * The `HSPolicy` object that we configured
4. **Send the response:** The response is sent from the Ionic to the native side.
5. **Handle the response:** The native side calls the `HSBotDefender/handleBlockResponse` function. This function presents a challenge to the user when the provided response is a blocked response.

## Send your requests through the SDK and check for a blocked request

1. Export the `HumanManager` plugin.
2. Add the SDK's HTTP headers to your URL requests.
3. When a request is blocked, send the block response to the SDK.
4. Handle the challenge’s result. See [handle blocked requests](#handle-blocked-requests) for more information.

Below is an example implementation:

**`JavaScript`**

```javascript title="JavaScript"
import { registerPlugin } from '@capacitor/core';

export interface HumanPlugin {
    getHttpHeaders():Promise<{ value: string }>;
    handleResponse(value : any):Promise<{ value: string }>;
}

const Human = registerPlugin<HumanPlugin>('HUMAN');

const sendUrlRequest = async () => {
    const result = await Human.getHttpHeaders()
    const json = JSON.parse(JSON.stringify(result))
    const map = new Map(Object.entries(json))

    var xhr = new XMLHttpRequest()
    xhr.addEventListener('load', async () => {
        const challengeResult = await Human.handleResponse({ "value": xhr.responseText })
        const challengeResultJson = JSON.parse(JSON.stringify(challengeResult))
        const challengeResultMap = new Map(Object.entries(challengeResultJson))
        console.log("challenge result = ", challengeResultMap.get("value"))
    })
    xhr.open('GET', 'https://example.com')
    for (const [key, value] of map) {
        xhr.setRequestHeader(key, value as string)
    }
    xhr.send()
};
```

## Handle blocked requests

When the **Enforcer** blocks a request, it returns a JSON string in the response body with an HTTP status code of `403`, which includes metadata for the SDK. For example:

```json
{
  "vid": "928d7ab3-9cf1-11ee-a624-b802520f369f",
  "uuid": "fd01e6d6-9cf2-11ee-808c-acde48001122",
  "page": "...",
  "appId": "PXj9y4Q8Em",
  "action": "captcha",
  "collectorUrl": "https://collector-pxj9y4q8em.perimeterx.net"
}
```

Your app should pass the whole JSON to the SDK via the `HSBotDefender/handleBlockResponse` function. If not, the SDK won't present a challenge to the user.