Installing and Configuring the eG Mobile Agent for Capacitor Applications

Capacitor is an open-source native runtime created by Ionic that lets you build cross-platform mobile and web applications using web code like JavaScript, HTML, and CSS. It wraps your web app inside a native container to run seamlessly on iOS, Android, and as a Progressive Web App (PWA).

By RUM-enabling applications developed using the Capacitor runtime, you can monitor in real-time, the experience of application users, and rapidly determine the source of poor UX. The first step to this is to install and configure the eG mobile agent on the target application's host.

For this, follow the steps below:

  1. Login to the application host.

  2. Then, open the browser, connect to the eG management console, and then login to the eG administrative interface.

  3. Follow the Infrastructure -> Add /Modify menu sequence. Figure 1 will appear. In Figure 1, pick Mobile RUM as the Component type, and click the Add New Component button to add a new Mobile RUM component.

    Selecting Mobile RUM as Component type

    Figure 1 : Selecting Mobile RUM as the Component type

  4. Figure 2 will then appear. Provide a Nick name for the Capacitor application you want to monitor.

    Figure 2 : Adding the target Capacitor application as a Mobile RUM component

  5. Then, select the Mobile RUM collector to which the eG Mobile Agent should send the performance metrics it gathers from the target application.

  6. Next, assign a Remote agent to the Mobile RUM component. This is the agent that will pull metrics from the Mobile RUM collector and reports the same to the eG manager.

  7. To install the eG mobile agent for Capacitor, set Application type as Hybrid.

  8. Finally, click the Add button.

  9. Figure 3 will then appear. Proceed to download the eG mobile agent from the manager. For that, in the right panel of Figure 3, first click on the Capacitor button. Then, click on the Download button that corresponds to the Gradle version in use in your environment. For instance, if the target application uses Gradle version 7.x or below, then click the Download button against Download Agent for Capacitor - Gradle Version 7.x and below (see Figure 3).

    Downloading eG Mobile Agent for Capacitor Gradle Version 7x or below

    Figure 3 : Downloading eG Mobile Agent for Capacity where Gradle version 7.x or below is used

    Likewise, if the Gradle version in use is 8.x or above, then click the Download button against Download Agent for Capacitor - Gracle Version 8.x and above (see Figure 4).

    Downloading eG Mobile Agent for Capacitor Grade Version 8.x or above

    Figure 4 : Downloading eG Mobile Agent for Capacity where Gradle version 8.x or above is used

  10. The eG Mobile agent will be downloaded as a zipped file. Extract the contents of this file to any location on the application host.
  11. Now, at the command prompt, switch to the extract location of the eG mobile agent plugin, and run the following commands one after another:

    npm installl

    npm run build

  12. Then, switch to the application's root directory and run the following command to install the eG mobile agent:

    npm install <PATH>\eginnovations-capacitor-plugin

    When issuing the command, make sure you replace <PATH> with the download path of the eG mobile agent.

  13. Once the eG mobile agent is installed, you need to instrument the target application by injecting the RUM code snippet in it. For that, do the following:

    1. Login to the eG administrative interface of the eG manager where the Capacitor application has been managed.

    2. Follow the Admin -> Infrastructure -> Add/Modify menu sequence.

    3. Select Mobile RUM as the Component type in the page that appears. All managed mobile RUM components will be displayed.

    4. In the list, locate the component that you added for the target Capacitor application and click the Modify button corresponding to it.
    5. In the page that appears next, click Capacitor in the right panel. Figure 5 will then appear. Click on the Copy to Clipboard button above the code snippet displayed against 'Include this line...'.

      Copying eG RUM Code Snippet for Instrumenting Capacitor App

      Figure 5 : Copying the code snippet to be inserted in the index.html file of the Capacitor application

    6. Now, edit the index.html file (in the src/ directory). This serves as the main entry point and the root HTML shell for your web-based application before Capacitor packages it into a native mobile container. In the file's header, insert the code snipped to copied to clipboard at step (e) above.

    7. Finally, save the file.
  14. If the underlying native platform is Android, then you have to make the following configuration changes additionally:

    • First, you need to update the project-level build.gradle file (located in the root directory of the target Android project) with dependencies related to the eG mobile agent. For that, you need to edit the file and include the following lines in it:

      Copy
      buildscript {
      repositories {
      flatDir {
      dirs '../node_modules/eginnovations-capacitor-plugin/eg-agent'
      }
      }
      dependencies {
      classpath fileTree(include: ['*.jar'], dir: '../node_modules/eginnovations-capacitor-plugin/eg-agent')
      }
      }
    • Then, save the file.

    • Similarly, you will have to update the application-level build.gradle file (located in the app/ directory) with the dependencies related to the eG mobile agent. For that, you need to edit that file and include the following lines in it:

      Copy
      repositories {
      flatDir {
      dirs '../../node_modules/eginnovations-capacitor-plugin/eg-agent' }
      }
      apply plugin: 'EgAgentGradlePlugin' //Gradle 8
      apply plugin:'eg' //Gradle 7
      //Gradle 7
      dependencies {
      implementation fileTree(dir: '../../node_modules/eginnovations-capacitor-plugin/eg-agent' , include: ['*.jar'])
      }
    • Next, save the file.

    • Now, proceed to edit the gradle.properties file (in the Android project's root directory), and add the eG mobile agent plugin to the 'ignorelist' of the file, as shown below:

      Copy
      android.jetifier.ignorelist=rewriter-agent-2.1.3.jar //Gradle 7 
      android.jetifier.ignorelist= EgAgentGradlePlugin-1.0.0.jar //Gradle 8

      This instructs the Android Gradle Plugin (AGP) to skip the automatic Jetifier migration process for eG mobile agent libraries. Its because this process may sometimes spew errors and cause application crashes.

    • Then, save the gradle.properties file.

    • Next, you need to allow the target application to perform network operations. For that, you need to set the following permissions for the application:

      • android.permission.INTERNET - This permission allows the application to perform network sockets.

      • android.permission.ACCESS_NETWORK_STATE - This permission allows the application to access information about networks.

      To allow these permissions, do the following:

      • Edit the AndroidManifest.xml file in the root of the project source set.

      • Under the manifest tag of the file, specify the following entries:

        Copy
        <uses-permission android:name="android.permission.INTERNET" />
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
      • Also, ensure that `android:usesCleartextTraffic="true"` is added in the <application> tag, as shown by the entry highlighted in Bold below:

        <application android:name=".MyApplication" android:theme="@style/AppTheme" android:usesCleartextTraffic="true">

        This allows the application to transmit over unencrypted HTTP connections.

    • Next, proceed to edit the MainActivity.java file (in the [YourProjectFolder]/android/app/src/main/java/[your]/[package]/[name]/ directory), and include the following 'import' statements in the file. These statements instruct the compiler to load the eG mobile agent and all its dependent classes and packages.

      Copy
      import com.eginnovations.capacitor.plugin.eGCapacitorPlugin;
      import com.eg.agent.android.eGAndroidAgent;
      import com.eg.agent.android.AppPlatform;
      import android.os.Bundle;
      import java.util.ArrayList;
      import com.getcapacitor.Plugin;
    • Next, inside the onCreate method, initialize the eG mobile agent by inserting the following code:

      @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);

      eGAndroidAgent.withCollectorHost("<APP_TOKEN>","<Collector_Host>").start(getApplicationContext()); eGAndroidAgent.setAppliactionPlatform(AppPlatform.Capacitor);

      // Initializes the Bridge

      this.init(savedInstanceState, new ArrayList<Class<? extends Plugin>>() {{

      // Additional plugins you've installed go here

      add(eGCapacitorPlugin.class);

      }});

      }

      private void init(Bundle savedInstanceState, ArrayList<Class<? extends Plugin>> classes) {

      }

      After inserting, make sure you replace the variables highlighted in Bold in the code above with the following values:

      • <APP_TOKEN>: Replace this with the value displayed against 'Site_Name' in the code snippet of Figure 5.

      • <Collector_Host>:  Replace this with the value displayed against 'beacon-url' in the code snippet of Figure 5.

    • Finally, save the file.

    • Clean and build the project in Android Studio. Run it on a simulator or mobile device:ionic cap build android

  15. If the target application is an ionic Angular application, then you have to make the following configuration changes additionally:

    • Edit the application.json file in the application's root directory and include the following lines in it:

      Copy
      "assets": [
      {
      "glob": "**/*.svg",
      "input": "node_modules/ionicons/dist/ionicons/svg", "output": "./svg"
      },
      {
      "glob": "**/egmobilerum.js",
      "input": "node_modules/eginnovations-capacitor-plugin/src", "output": "./"
      }
      ]

    • Then, save the file.

  16. If the target application is a React application, then you have to make the following configuration changes additionally:

    • Edit the capacitor.config.json file (in the root directory of the target application) and change bundledWebRuntime to true and webDir to “public”, as shown below:

      "bundledWebRuntime": true,

      "webDir": "public"

      }

      By default, for React applications, bundledWebRuntime is set to false. In this case, your bundler will handle compiling and optimizing the Capacitor code automatically.

      By setting this flag to true on the other hand, you instruct Capacitor to generate a standalone capacitor.js file and copy it into your web assets directory (webDir) during a build or copy command.

    • Then, save the file.

  17. If the you are monitoring a Capacitor-powered iOS application, then you have to make the following configuration changes additionally:

    • First, open the target application in Xcode and open the AppDelegate.swift file (within your native iOS platform directory at the ralative path, ios/App/App/). This file serves as the main entry point and operational heart of your native iOS app . Now, edit this file to add the following import statement:

      import eGMobileAPM

      An import statement included in the AppDelegate.swift file maks external frameworks, system libraries, and native bridge modules available to your app's main entry point. The above import statement therefore, makes sure that the eG mobile agent is available to the target application's entry point,

    • Next, in the same file, inside didFinishLaunchingWithOptions method, add the below line:

      egAPM.sharedInstance().start(appToken:"<APP_TOKEN>", collectorHost:"<Collector_Host>”)

      After inserting the above line, make sure you replace the variables in Bold with the following values:

      • <APP_TOKEN>: Replace this with the value displayed against 'Site_Name' in the code snippet of Figure 5.

      • <Collector_Host>:  Replace this with the value displayed against 'beacon-url' in the code snippet of Figure 5.

      The didFinishLaunchingWithOptions method in AppDelegate.swift is the primary entry point called by iOS right after your native app finishes launching, but before the first screen appears. By including the above statement under this method, you are instructing the compiler to start the eG mobile agent as soon as the native app is launched.

    • Then, save the file.

    • Finally, clean and build the project in Xcode. Run it on a simulator or mobile device:

      ionic build

      npx cap sync ios

  18. Finally, proceed to instrument the application, so the eG mobile agent is able to collect the required metrics from it. For that, edit the app.component.ts file (which you will find the src/app folder), and add the following lines to it:

    Copy
    import {NavigationStart, NavigationEnd, NavigationError, NavigationCancel,
    RoutesRecognized, ActivatedRoute} from '@angular/router'
    import {eGCapacitorPluginWww} from "eginnovations-capacitor-plugin";
    declare var EGRUM: any;
    export class AppComponent {
    deviceInformation = '';
    resourceInformation = '';
    applicationInformation = '';
    activityName = '';
    country = '';
    device = '';
    os = '';
    applicationName = '';
    osVersion = '';
    isEnabled = true;
    constructor( private platform: Platform, private router: Router, private splashScreen: SplashScreen, private activatedRoute: ActivatedRoute, private statusBar: StatusBar
    ) {
    this.initializeApp();
    }
    initializeApp() { this.platform.ready().then(() => {
    this.statusBar.styleDefault(); this.splashScreen.hide();
    });
    }
    // eG RUM Monitoring Starts
    ngOnInit(): void {
    this.router.events.subscribe(event => {
    let componentName = (this.activatedRoute.component !== null) ?
    this.activatedRoute.component['name'] : 'default';
    if (event instanceof RoutesRecognized) {
    let actSnap = event.state.root;
    const childLength = actSnap.children.length;
    while (actSnap && childLength > 0) {
    actSnap = actSnap.children[0];
    if (actSnap && actSnap.component && actSnap.component['name']) {
    componentName = actSnap.component['name'] || componentName;
    }
    }
    }
    if (event instanceof NavigationStart) {
    if (typeof EGRUM !== 'undefined') {
    EGRUM.vPage('markVirtualPageStart');
    EGRUM.vPage('page', componentName);
    EGRUM.vPage('meta', 'component', componentName);
    }
    } else if (event instanceof NavigationEnd) {
    if (typeof EGRUM !== 'undefined') {
    EGRUM.vPage('markVirtualPageEnd', {
    status: 'completed', url:
    window.location.href
    });
    }
    } else if (event instanceof NavigationError) {
    if (typeof EGRUM !== 'undefined') {
    EGRUM.vPage('markVirtualPageEnd', {
    status: 'error',
    url: window.location.href,
    explanation: event['error'] && event['error'].toString()
    });
    }
    } else if (event instanceof NavigationCancel) {
    if
    (typeof EGRUM !== 'undefined') {
    EGRUM.vPage('markVirtualPageEnd', {
    status: 'aborted',
    url: window.location.href,
    explanation: event['reason'] || ''
    });
    }
    }
    });
    this.load();
    }
    async load() {
    try {
    let result = await eGCapacitorPluginWww.isEnabled();
    this.isEnabled = result['isEnabled'];
    } catch (err) {
    console.log('AppComponent::din:error:::' + err);
    }
    try {
    let result = eGCapacitorPluginWww.getOSVersion(); const
    JSobj = JSON.parse(JSON.stringify(result));
    this.osVersion = JSobj.osVersion;
    } catch (err) {
    console.log('AppComponent::osVersion:error:::' + err);
    }
    try {
    let result = await eGCapacitorPluginWww.getDevInfo();
    this.deviceInformation = result['deviceInformation'];
    } catch (err) {
    console.log('AppComponent::din:error:::' + err);
    }
    try {
    this.applicationInformation = (await
    eGCapacitorPluginWww.getAppinfo())['applicationInformation'];
    } catch (err) {
    console.log('AppComponent::ain:error:::' + err);
    }
    try {
    this.resourceInformation = (await
    eGCapacitorPluginWww.getResInfo())['resourceInformation'];
    } catch (err) {
    console.log('AppComponent::rin:error:::' + err);
    }
    try {
    this.activityName = (await
    eGCapacitorPluginWww.getCurrentActivityName())['activityName'];
    } catch (err) {
    console.log('AppComponent::at:error:::' + err);
    }
    try {
    this.country = (await eGCapacitorPluginWww.getUserCountry())['country'];
    } catch (err) {
    console.log('AppComponent::cty:error:::' + err);
    }
    try {
    this.device = (await eGCapacitorPluginWww.getDeviceName())['deviceName'];
    } catch (err) {
    console.log('AppComponent::odvn:error:::' + err);
    }
    try {
    this.os = (await eGCapacitorPluginWww.getBaseOs())['osName'];
    } catch (err) {
    console.log('AppComponent::os:error:::' + err);
    }
    try {
    this.applicationName = (await
    eGCapacitorPluginWww.getAppName())['appName'];
    } catch (err) {
    console.log('AppComponent::appn:error:::' + err);
    }
    if (typeof EGRUM !== 'undefined') {
    EGRUM.setDeviceDetails(this.deviceInformation);
    EGRUM.setAppDetails(this.applicationInformation);
    EGRUM.setResDetails(this.resourceInformation);
    EGRUM.setActivity(this.activityName);
    EGRUM.setUserCountry(this.country);
    EGRUM.setDeviceName(this.device);
    EGRUM.setBaseOS(this.os);
    EGRUM.setAppName(this.applicationName);
    EGRUM.setOSVersion(this.osVersion);
    EGRUM.isEnabled(this.isEnabled);
    }
    }
    // eG RUM SPA Monitoring Ends
  19. Finally, save the file.

Troubleshooting

Troubleshooting the Collector Reachability Issue

The eG manager might be running with self - signed SSL certificates in some deployments. A recent enforcement for Android 7 and above blocks outbound connections from mobile applications on Android to 3rd party self-signed applications / services. This means that, if a mobile application that is running on Android 7 (or above) is being monitored as a Mobile RUM component, then the eG mobile agent installed on such an application will not be able to reach the RUM collector on the eG manager. To allow this communication therefore, do the following:

  1. Create a network_security_config.xml file in the \platforms\android\app\src\main\res\xml\ directory.

  2. In the file, include the following lines of code:

    <network-security-config>

    <base-config cleartextTrafficPermitted="true"> <trust-anchors>

    <certificates src="system" />

    </trust-anchors>

    </base-config>

    </network-security-config>

     

  3. Save the file.

Troubleshooting JS Errors in Ionic Angular Applications

To resolve such issues, do the following:

  1. Edit the app,module.ts file in the [Project-Root]/src/app/ directory.

  2. Append the following lines of code in the file.

    import { ErrorHandler } from '@angular/core'; declare var EGRUM: any;

    @Injectable()

    export class EGRUMErrorHandler implements ErrorHandler { handleError(err: any): void {

    EGRUM.onerror({ message: err.message,

    filename: err.filename, lineNumber: err.lineNumber, columnNumber: err.columnNumber, stack: err.stack,

    meta: { type: "Internal Error." }

    });

    }

    }

    @NgModule({

    declarations: [AppComponent], entryComponents: [],

    imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule], providers: [

    {provide: ErrorHandler, useClass: EGRUMErrorHandler}

    ],

    bootstrap: [AppComponent]

    })

  3. Finally, save the file.