Going Mobile: Wrapping an existing web application in Cordova/Phonegap

Going Mobile: Wrapping an existing web application in Cordova/Phonegap

There are many choices to build mobile applications, from native to the growing popularity of hybrid development, with everything in between. In all of these cases, as a developer you would be writing a brand new mobile application from scratch with the ultimate goal of deploying to one the app stores. Let’s say that a company has an existing web application and for reasons we will not debate here, management has decided that this web application is to be packaged and delivered as a mobile app available from the main app stores. How would you go about it from a development perspective and what would be some of the pitfalls and difficulties to take into account when engaged in this endeavor? This article will attempt to cover these and offer some solutions based on actual experience.

Design

The first and most crucial problem that you will have to resolve before doing anything is ensuring that:

  • Your web app is responsive
  • Your web app uses mobile friendly form controls

The second point is actually quite important if you’re using custom controls that will not be rendered natively by the mobile browser (I am looking at you Bootstrap dropdowns). You will have to scour your application on a mobile screen to ensure that the experience is consistent and frustration free for your target users. I emphasized target here because if your goal is to keep your application available through the web but still be available as a mobile application, I can almost guarantee that you will run into design issues where one platform will have to be favored over the other for optimal design so be prepared to make these choices when they come up.

Assuming that your design is now mobile ready. How do you go about wrapping into something that will feel native to your users?

Phonegap/Cordova and the InAppBrowser

Adobe PhoneGap is a distribution of Apache Cordova and Cordova is an open-source mobile development framework that allows you to use standard web technologies — HTML5, CSS3, and JavaScript for cross-platform mobile development. In simple words use standard web development tools to create and deploy mobile applications from a single codebase across different platforms. Phonegap offers some additional enterprise services for the development and deployment of your Cordova application but in essence you will always be working with Cordova under the hood.

What’s interesting about Cordova is that it can be extended using plugins which allow your app to use native device capabilities beyond what is available to pure web apps. That is how your standard HTML, CSS and Javascript codebase can hook into the phone’s camera or microphone to perform native functions, reinforcing the illusion of native to your app’s user. One of these plugins that can be made use of to wrap an existing application into a native app is the InAppBrowser who started as an independently developed plugin before being incorporated as a core Cordova plugin. It’s basically a child web browser that allows you to access third party web content. Wrapping an existing web application as a native application comes down at this point to loading said web application in an InAppBrowser window and managing the whole mobile app experience.

In practice, the loading is the easy part, with the managing of the mobile experience come the hard parts.

Cross Window Communication

Outside of just authentication, there will be many instances where you will find yourself wanting to communicate values between the wrapper app and the wrapped app in the inAppBrowser window. This great article by TJ VanToll lays the foundation for how to to just that even though it dates from 2013. Basically by making use of the inAppBrowser executeScript function, and using localStorage, you can exchange values between both windows. It’s not a standard way of operating but while waiting for Cordova to implement the window.postMessage specification in the InAppBrowser, this remains the most effective way of going about cross window communication.

Authentication and Session Management

If your application only consist off content that does not require authentication, you’re home free. Skip the rest of the article and enjoy yourself a cold drink. For the majority of cases the existing application is without a doubt functional only after authentication. With authentication also comes session management not only in the context of your application but also in the context of your user being on a mobile phone with the expected corresponding behavior. The following questions need to be answered

  • How long does the session last once the user is authenticated? In web applications, users are used to re-authenticating every time their session expire but on mobile, the expectation is to authenticate once and forget it, or use other less intrusive mechanisms like fingerprint reading or pin entering when security must be enforced. The takeaway is that you should not make the user have to enter a username and password every time they open the app if they really don’t have to.
  • Is your Forgot Password application flow mobile friendly? Does it require users to perform steps (Captcha) that are easy to do on a computer but would be more challenging on a mobile device? If not, you will have to adjust your flow to use more mobile friendly techniques (verification codes sent by SMS or Email).
  • What happens to your application when the user navigates away from it? Do not assume that your application will always be front and center, what happens when a call comes in and last longer than your session duration? What happens if the user sends the application to the background and then comes back to it a couple of days later? How would you know the state of the application at that time?

These questions show that even though the goal is to simply wrap an application in an hybrid app, to ensure an optimal mobile experience you will sometimes have to write additional code in the hybrid app to handle these different situations. For authentication and session management, the general idea is for also the hybrid wrapper to be aware of the authenticated and session state of your application.

Cookie Authentication

If your application uses cookies for authentication and session management and you don’t need to add an extra layer of security or convenience like fingerprint authentication, you will need to make sure that when opening the InAppBrowser window, you set the proper option for the window to remember cookies, otherwise if you kill the app and re-open it, your session cookies will be gone and the user will need to re-authenticate:

var ref = (url, target, options);

From the documentation:

options: Options for the InAppBrowser. Optional, defaulting to: location=yes. (String)

The options string must not contain any blank space, and each feature’s name/value pairs must be separated by a comma. Feature names are case insensitive. All platforms support the value below:

location: Set to yes or no to turn the InAppBrowser‘s location bar on or off.

clearcache: set to yes to have the browser’s cookie cache cleared before the new window is opened

clearsessioncache: set to yes to have the session cookie cache cleared before the new window is opened

The clearcache and clearsessioncache options are available on both Android and iOS and for clearsessioncache it should be set to no to ensure that your session cookies are remembered.

Token Authentication

If you’re using a token based authentication strategy and want to add fingerprint or pin-based authentication, you will need add extra code to the hybrid app to check for the state of the user when the app opens and present them with either a login screen or a fingerprint/pin reader. Refer to the Cross Window Communication section on how to communicate this state between the wrapper and wrapped apps.

External Links

A (nasty) little gotcha from using the inAppBrowser is that clicking on a link to external content, while you are in a inAppBrowser window will load that content in the inAppBrowser window you are using which leads to the following scenario:

  • User is enjoying your app thinking it’s native as your design job is excellent.
  • User sees a link to let’s say a Twitter page and “clicks” on it
  • The Twitter page loads in the InAppBrowser window, replacing your app with the Twitter page where your app screen used to be.
  • Extreme confusion ensues as the task manager shows that the user is indeed using your app, but they have no way to get back to your app content on iOS, or have to use the Back button on Android, and at this point the magic of native feel is broken.

The expected behavior would have been for the link click to open in a new OS Browser window, keeping the application intact and allowing the user to get back to it once they are done.

The solution in general is to track every external link with a script and open them using the window.open(url, '_system') call as illustrated here. Remember that this script will have to run in your wrapped app to work otherwise you will need to communicate the link url back to the wrapper app and issue the window.open call.

Android Only: Back Button

On Android you will have to be careful and plan out what happens when the user clicks on the Back button whether it’s a hardware or software button. If your wrapped app is a SPA, this can leads to some weird situations with your app state.

First thing to know is that there is a configuration for it in the InAppBrowser launch options:

hardwareback: set to yes to use the hardware back button to navigate backwards through the InAppBrowser‘s history. If there is no previous page, the InAppBrowser will close. The default value is yes, so you must set it to no if you want the back button to simply close the InAppBrowser.

If it is set to yesand your SPA handles back history fine, if the user gets back to the first page in your history and touches the Back button again, they will be taken back to the entry page of your wrapper app! Again not optimal and it breaks the experience of native and leaves the user confused again. One way to handle it would be to listen to the exit event on the InAppBrowser window so that when it is closed, the wrapper itself also is closed. Check this StackOverflow issue for alternatives.

Angular Only: ngZone for event handlers

After working with Cordova/Phonegap for a while and installing plugins, you’ll become familiar with how Cordova exposes functionality through events and event callbacks or promises. One gotcha if you’re working with Angular (>v4) is that these are events that are happening outside of Angular and if you remember even from AngularJS, any event happening outside of AngularJS needs to be synced with the AngularJS digest cycle using the $scope.apply() function. It’s no different in Angular expect now that Angular run in zones and uses the ngZone.run() function to re-enter the Angular zone. If you have Cordova plugin events firing and you are not able to tap into them in Angular, make sure to capture the event within a run function call as illustrated here in this example service for the Back button event being fired.

import { Injectable, NgZone } from '@angular/core';
@Injectable()
export class BackButtonService {
constructor(private logger: DebugLogService,
private ngZone: NgZone) {
document.addEventListener('backbutton', () => {
this.ngZone.run(() => {
console.log('Back button has been pressed')
});
}, false);
}
}

Summary

Although the initial goal of wrapping an existing web app into a native mobile app might look simple enough with Cordova/Phonegap, in practice there a quite a few pitfalls in making sure that the experience is optimal for users and fulfills their expectations for what a native app experience is. Behind the scene there will be quite a few orchestrations to put in place to maintain the illusion of native. I would then only recommend this approach as a stop gap measure while either a more appropriate native or hybrid app is being developed. Even they don’t work on Safari yet thus making them a more limited choice at this point, Progressive Web Applications are also a very viable option when targeting mobile applications.

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s