I'll post a link to a blog post about this with more details/examples, but essentially this boils down to three things:
- Modifying the requests from PhoneGap and then detecting that on your server
- Making sure the proper Javascript APIs are in the right place
- Detecting when to show/enable PhoneGap-specific functionality
The way I'm currently accomplishing this is as follows:
1) Modifying the requests from PhoneGap
You can add a custom string to the User Agent from your PhoneGap app and then search for that custom string on the server. The easiest way to do that (on Android) is in your platforms/android/src/path/to/your/app/[app_name].java
. In the onCreate
method, after the super.loadUrl(Config.getStartUrl());
line, add:
String ua = this.appView.getSettings().getUserAgentString();
this.appView.getSettings().setUserAgentString(ua + " your_custom_string");
2) Making sure the proper Javascript APIs are in the right place
When you build a PhoneGap app and run it with a local source, there's a fallback for the actual Javascript APIs PhoneGap uses. If running locally, you don't need the cordova.js
or phonegap.js
file in your project directory at all. You can find the files you need in platforms/android/assets/www
. You're looking for cordova.js
, cordova_plugins.js
, and the entire plugins/
directory. In your web app, then, you need to make sure the folder you're pointing to for cordova.js
also has the plugins/
directory. For example:
<script type="text/javascript" src="/js/cordova.js"></script>
Means everything should be in your webroot/js/
folder.
3) Detecting when to show/enable PhoneGap-specific functionality
This is as easy as reading the User Agent for your_custom_string
from earlier and enabling/disabling features. You're not going to want to load the cordova.js
script unless the viewer is coming from PhoneGap (things get weird otherwise), and make sure you set up an event listener on the deviceready
event, and do any PhoneGap-specific code after that's fired.
The forthcoming blog post will have a simple example using Ionic and PhoneGap's Contacts API.
And that's it! I'm really excited about the potential this opens for progressive enhancement. This lets me support both mobile web and native (Android, and likely iOS) with ~99% of the same codebase, and allows me to only enable features if I know the user has them. It's like hacky feature detection on steroids.