Home > Articles

Apache Cordova and Server-Side Technologies

If you want to use Apache Cordova with apps that make use of server-side scripting technologies, you've probably been stymied on how to proceed. John M. Wargo, author of Apache Cordova 4 Programming, explains why this process isn't as simple as it seems. However, not only is it possible, but a little effort yields reusable code for converting your desktop web and native mobile apps.
Like this article? We recommend

Like this article? We recommend

Many developers are looking to mobilize existing web applications, and they see Apache Cordova as a useful way to do so. They're right. Apache Cordova provides a great way to use web development skills and web technologies to deliver native mobile (and desktop) applications.

For many years now, I've been trolling the PhoneGap Google Groups and Stack Overflow Cordova sites (trolling as in fishing, not in the Internet sense), trying to answer any questions I can. A common question is, "How can I get my [technology_name]-based app to work in Cordova/PhoneGap?" replacing [technology_name] with server-side scripting technologies such as ASP.NET, JSP, node JS, and PHP.

Unfortunately, the short answer to the question above is, "You can't." Also, as React Native (Facebook), NativeScript (Telerik), tabris.js (EclipseSource), and other options gain popularity with developers, it's important to be clear that the same answer applies for those frameworks as well.

The long answer consumes the remainder of this article. Spoiler alert: You'll have to create a new web application to run in the Apache Cordova container, plus rework your existing back-end server app to accommodate this new approach. The good news is that you'll be able to do this using code from the existing app as a starting point, leveraging much of the HTML, JavaScript, CSS, and server-side scripting code your app uses today.

A Quick Intro to Apache Cordova

It's clear to me that developers asking about server-side scripting technologies and Apache Cordova don't really understand what Apache Cordova is. So, before we go any further, I'll provide a quick background on Apache Cordova. For much more detail, please take a look at Apache Cordova 4 Programming.

Apache Cordova is an open source framework that allows web developers to create native mobile (and desktop) applications. Developers code a web application that provides the UI and business logic the app requires and then uses tools provided by the Cordova team, along with the native SDKs for each target platform, to package the web application into a native application container that simply renders the web app (like the browser does today). When the app launches, the native app displays a full-screen WebView (basically a browser window without any chrome) and then loads the web app into the WebView. At this point, the WebView takes over, and the users interact directly with the web content, just as they would in a browser. The initial benefit here is that the app is now a native app that can be deployed through app stores and shows up as an app icon on the device's home screen.

At this point, you're probably asking, "Then why would I need Cordova? Users can put an icon for a web app on their home screen today in just a few simple steps."

The answer comes down to accessing native APIs. One of the things that makes native mobile applications more engaging than web applications is that native applications have access to more local capabilities than a browser app has. Native applications have access to all of the capabilities exposed through the mobile operating system APIs and applications. Mobile web browsers added capabilities that allow web applications to access the camera, geolocation or file system, and more, and those capabilities will continue to grow over time. For now, though, only native applications can access native capabilities; for example, the contacts database, calendar, or near field communications (NFC).

Apache Cordova bridges that gap by providing a JavaScript-to-native bridge that enables web applications to make calls to native APIs. With that in place, Cordova delivered an open plug-in architecture plus a core set of plug-ins that enable developers to access some common APIs from their web applications running in the Cordova container. Where the Cordova team doesn't publish a plug-in exposing the native capabilities that a developer needs, it's easy to find a plug-in that does, or to build a custom plug-in. The result is a native mobile application executing web content that has access to native capabilities.

Developers like Cordova because they can get more use out of their existing web apps. They simply need to transform the web app into a format that can run in the Cordova container.

What Are the Issues with Server-Side Scripting Languages and Cordova?

With that background on Apache Cordova in mind, let's consider why web apps written using server-side scripting languages can't run in an Apache Cordova container. If you're reading this article, I have to assume that you know more about server-side scripting technologies than you do about Apache Cordova. In case I'm wrong, though, I'll use this section to highlight how server-side scripting languages work, and then wrap up by explaining why they're unsuitable for use with Apache Cordova.

Server-side scripting languages are used to build dynamic or data-driven websites. A developer embeds script code within a web page; the code, which can do almost anything, is used to create or change content on the page depending on conditions embedded in the code. Special software deployed on a web server processes pages before they're delivered to user agents (typically a web browser). The server process parses the script code and then executes it, replacing the embedded code with the results of the code execution.

To demonstrate this process, take a look at some sample code from the PHP developer guide:

<html>
  <head>
    <title>PHP Test</title>
  </head>
  <body>
    <?php echo '<p>Hello World</p>'; ?>
  </body>
</html>

In this example, as the web server gets ready to deliver the page, the php server task parses the PHP code within the body tag (the boldfaced code in the example) and replaces it with the result of executing the code. In this case, the PHP server returns the text <p>Hello World</p>. The server then returns the following page script to the requesting browser:

<html>
  <head>
    <title>PHP Test</title>
  </head>
  <body>
    <p>Hello World</p>'
  </body>
</html>

As I mentioned previously, the embedded server-side code can do almost anything. Typically, it's used to retrieve data from a database or application server, customize a page to the user's preferences, and so on. The web server delivers only HTML pages, customized for each request as shown in Figure 1. Web developers create static web pages using the necessary HTML, JavaScript, and CSS code, and then the PHP code embedded within the page gets just-in-time custom content based on the business logic embedded in the PHP code.

Figure 1 Serving dynamic web pages.

This approach won't work in an Apache Cordova app because it relies on a server process to parse the server-side scripting code and update the page before passing it to the rendering engine (the browser). In the Apache Cordova use case, the web application is prepackaged within the Cordova container, not retrieved from a web server. There simply are no available implementations of the server-side scripting engines that would run within the Cordova container.

If you think about it, the scenario described in the previous paragraph is the reason why the Web 2.0 approach was created. It allows developers to deliver dynamic apps from a static app, but the data is retrieved from the app server, not from web pages.

Leveraging Existing Dynamic Web Pages in an Apache Cordova App

Now, you may be thinking, "Couldn't I create a Cordova app that simply displays the remote web content within the native container?" Yes, you can. By default, an Apache Cordova app opens the local index.html file at launch. The developer can point that startup page to a different file packaged within the application, myapp.html for example, or it could point to a remote server URL such as http://myapp.mydomain.com. When the app launches, the user would see a blank screen while the remote content is retrieved, parsed, and rendered.

This approach would work, but with problems; for example, Apple isn't fond of publishing apps like this in the App Store. Also, your existing app running in the Cordova container wouldn't make use of any of the native APIs that Cordova exposes to the app through plug-ins. You could rework the app so that it detects whether it's running in a Cordova app, and then enable the native capabilities in that case, but that technique adds a level of complexity to your app that may be difficult to maintain. Ultimately you would be maintaining two versions of your app in the same code base.

Another problem is what happens when the device running the app doesn't have a network connection: The app won't be able to display anything. A Cordova app doesn't cache content like the browser does; it loads everything dynamically at startup. A Cordova app typically has all or most of its web content packaged within the app, allowing it to operate with or without a network connection. Not the best user experience when the app loads to a blank screen and an error dialog.

Reworking an Existing App into Apache Cordova

The solution to these scenarios? Rework the app in the Web 2.0 style, and it will fit well into the Cordova architecture. The app has to be rewritten so that the web application content can be packaged into the Cordova container without needing server-side components to manage the content. To use this design, you'll have to create some way for the web app to obtain the data it needs from the server. The difference is that the server will no longer be delivering web pages crafted in HTML; instead, it merely delivers data and lets the app handle rendering it (as shown in Figure 2).

Figure 2 Serving the Web 2.0 approach.

Migrating an existing dynamic web app built with server-side scripting languages to Apache Cordova requires the following:

  • Create one or more web services that expose the data used by the existing dynamic web app. In every place where the dynamic web app reaches out to a database or app server for data using the server-side scripting language, replace that code with a call to a web service.
  • Rework the existing web app into the Web 2.0 style. Here the app's HTML pages (or page, in a single-page app) are self-contained and can easily be packaged into a Cordova container. The app still uses the network to retrieve data as needed, but at least the app will run (and display something) when the device is outside network coverage.

As a bonus, you'll be able to reuse much of your existing code:

  • You don't have to throw away the web application code. What you have today still works; all you have to change is the areas in the app where the code reaches out to an external data source to obtain data that's rendered within the app. Replace server-side scripting code with AJAX requests and some code that renders the results when they come back from the server, and you're done.
  • You may be able to keep your server-side scripting code. Server-side scripting technologies can usually be used to create web services as well, so all you'll need to do is wrap the existing code into web services, and you're all set.

The only real challenge you'll face is replicating any security required by the application, which is easily addressed by adding a login page to the app that validates the user's credentials against the organization's identity-management system. If the user can't log in, display an error page instead of any protected data. Additionally, be sure to encrypt any data that is cached on the device, to protect it from prying eyes if the device is lost or stolen.

With this approach, you'll also be able to leverage the work you've done in the desktop and native mobile-app versions of your app. The desktop browser doesn't have to use the dynamic web pages from the old approach; simply point the desktop browsers to the same web app content. Any services you create can be used just as easily, if you ever decide to deliver a native version of the app.

Conclusion

With the information provided in this article, you have the basic background needed to understand how to leverage existing dynamic web applications with Apache Cordova. You'll have work to do if you want to migrate your apps to the Cordova framework, but it shouldn't be too hard. As a bonus, you can easily leverage the work you've done across other channels, such as desktop web and native mobile apps, so this exertion is worth the effort.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020