Some initial WebView code for connecting to the server

Most of your Cordova app is developed using the web resources. After creating your Cordova app and adding the MobileFirst plug-in you can add MobileFirst functionality.

WebView files

In this example a simple index.html file creates the initial screen containing a single button. This button is defined in the imported index.js file.

Note: When running the Cordova CLI build or prepare command, the web resources in main [projectname]\www folder are copied to each platform's www folder ([projectname]\platforms\[platform]\assets\www). Therefore in this case you need to edit the main www copy if you are going to build with the Cordova command. If you are going to build with platform IDE such as Android Studio or Xcode, you need to edit the local platform copy.

After creating your Cordova app using the Apache tools and adding the MobileFirst plug-in, the index.html and JavaScript files do not include any examples of the MobileFirst API. Here is an example of accessing a server resource (adapter).

Note: You need to register your app before you can access the server. For more information, see Registering Cordova applications to MobileFirst Server.

The index.html file

The app starts up with the initial index.html The button is included in the html:

<div><button id ="resourceRequestBTN" style="float:left; margin-top:10px;">Resource Request</button> </div>
<html>
    <head>
        <meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">
        <meta name="format-detection" content="telephone=no">
        <meta name="msapplication-tap-highlight" content="no">
        <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
        <link rel="stylesheet" type="text/css" href="css/index.css">
        <title>Hello World</title>
    </head>
    <body>
        <div class="app">
            <h1>Apache Cordova</h1>
            <div id="deviceready" class="blink">
                <p class="event listening">Connecting to Device</p>
                <p class="event received">Device is Ready</p>
                <br />
            </div>
            <div><button id ="resourceRequestBTN" style="float:left; margin-top:10px;">Resource Request</button> </div>
        </div>
        <script type="text/javascript" src="cordova.js"></script>
        <script type="text/javascript" src="js/index.js"></script>
    </body>
</html>
The resourceRequestBTN button is defined in the index.js file.

The index.js file

The index.js adds the listener to the resourceRequestBTN button which calls the resourceRequestGetBalance function.

document.getElementById("resourceRequestBTN").addEventListener("click", resourceRequestGetBalance, false);
The resourceRequestGetBalance function requests the server resource (an adapter) and returns either the response or an error.
function resourceRequestGetBalance(){
try{
        var request = new WLResourceRequest('/adapters/account/balance', WLResourceRequest.GET); 
		request.send().then(
      	function(response) {
      	    var response = JSON.stringify(response);
      	 	console.log("response " + response);
      	 	alert(response);
          // success flow, the result can be found in response.responseJSON
      	},
      	function(error) {
              console.log("error " + error);
          // failure flow
          // the error code and description can be found in error.errorCode and error.errorMsg fields respectively
      	}
 		).fail(function(){
 			console.log("WLResourceRequest failure");
 		});
	}catch(err){
		console.log("exception:"+ err);
	} 	
}

For information on creating and deploying the adapter see Developing the server side of a MobileFirst application.

Testing the connection to the server without deploying an adapter

If you want to test the app registration and connection to the server without the need for deploying an adapter, you can test a request for an access token. If no security checks have been added to your app the access token will succeed once the registration and connectivity to the server are working.

To test the security token access replace the resource button with this button in the file:

<div id="btn1">   <button id ="getToken">getToken</button>  </div>

In the index.js file replace the resource button listener with the access token button listener for invoking getToken:

 document.getElementById("getToken").addEventListener("click", getToken, false);

and add the getToken function

function getToken() {
    WLAuthorizationManager.obtainAccessToken().then(function(token) {
        alert("success: "+JSON.stringify(token))
    },function(error) {
        alert("failure: "+JSON.stringify(error))
    });
}

If the connection succeeds you will see the contents of the token. If not the error is displayed.

The sample index.js file for the resource request check:

The entire index.js file for testing the resource request appears below.

var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicitly call 'app.receivedEvent(...);'
    onDeviceReady: function() {
        app.receivedEvent('deviceready');
        document.getElementById("resourceRequestBTN").addEventListener("click", resourceRequestGetBalance, false);
    },
    // Update DOM on a Received Event
    receivedEvent: function(id) {
        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');

        listeningElement.setAttribute('style', 'display:none;');
        receivedElement.setAttribute('style', 'display:block;');

        console.log('Received Event: ' + id);
    }
};

app.initialize();

function resourceRequestGetBalance(){
try{
        var request = new WLResourceRequest('/adapters/account/balance', WLResourceRequest.GET); 
		request.send().then(
      	function(response) {
      	    var response = JSON.stringify(response);
      	 	console.log("response " + response);
      	 	alert(response);
          // success flow, the result can be found in response.responseJSON
      	},
      	function(error) {
              console.log("error " + error);
          // failure flow
          // the error code and description can be found in error.errorCode and error.errorMsg fields respectively
      	}
 		).fail(function(){
 			console.log("WLResourceRequest failure");
 		});
	}catch(err){
		console.log("exception:"+ err);
	} 	
}