Integration with Ionic
  • 10 Aug 2023
  • Dark
    Light

Integration with Ionic

  • Dark
    Light

Article Summary

v3.0

The SDK can be integrated into Ionic projects.

Start the SDK

The automatic interceptor is not supported in Ionic, so any request from the JavaScript code has to be handled manually. Here is an example:

try {
    val policy = PXPolicy()
    policy.urlRequestInterceptionType = PXPolicyUrlRequestInterceptionType.NONE
    PerimeterX.start(application, "<APP_ID>", null, policy)
}
catch (exception: Exception) {
    println("failed to start. exception: $exception")
}

Setup a plugin

Configure the plugin in JavaScript. Here is an example:

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

const PerimeterX = registerPlugin<PerimeterxPlugin>('PerimeterX');

Setup a plugin in order to handle calls from the JavaScript code. Here is an example:

@CapacitorPlugin(name = "PerimeterX")
public class PerimeterxManager extends Plugin {

    String pxSolved = "solved";
    String pxCancelled = "cancelled";
    String pxFalse = "false";

    @PluginMethod()
    public void getHttpHeaders(PluginCall call) {
        HashMap headers = PerimeterX.INSTANCE.headersForURLRequest(null);
        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("value");
        JSObject ret = new JSObject();
        boolean handled = PerimeterX.INSTANCE.handleResponse(response, null, result -> {
            ret.put("value", result == PerimeterXChallengeResult.SOLVED ? pxSolved : pxCancelled);
            call.resolve(ret);
            return null;
        });
        if (!handled) {
            ret.put("value", pxFalse);
            call.resolve(ret);
        }
    }
}

Pass the SDK's HTTP headers to the JavaScript code and handle the response

In your JavaScript code, call those functions for every URL request to add those HTTP headers and handle the response. Here is an example:

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

  var xhr = new XMLHttpRequest()
  xhr.addEventListener('load', async () => {
    const challengeResult = await PerimeterX.handleResponse({ value: xhr.responseText })
    console.log("result = ", JSON.parse(JSON.stringify(challengeResult)))
  })
  xhr.open('GET', 'https://sample-ios.pxchk.net/login')
  for (const [key, value] of map) {
    xhr.setRequestHeader(key, value as string)
  }
  xhr.send()
};

Was this article helpful?