One of the advantages I mentioned about PhoneGap, was being able to write custom native code, and interface with it via JavaScript. Their Aren't great example of how to do this out there, so I figured a quick blog post was in order.
I search around for how to do this when getting started with PhoneGap, and the best example I could find was, Native messages for Android PhoneGap. Following this example, I was able to get my own Javascript interface working.
Basically you create a class (using java for android example):
I
create this private class in the main Java class which extends DroidGap (the class that boots up PhoneGap and creates the webview UI).
Then in your html you can call in javascript bridged Java functions like var myData = CUSTOM.getData(); which will return the java data (in this case a string) to the javascript. I have used the JS bride to begin new Android Activities, Close the WebView and move entirely to Native code. Background the WebUI to do something native for awhile, then return the WebView back to the front, Etc.
This can be done similarly for the iPhone and Objective-C to Javascript with PhoneGap. This lets you leverage extra native flexibility while still building the majority of your app as JS, CSS, and HTML.


Comments (5)
Thanks for the post. Do you know if it's possible to switch to another Activity or DroidGap subclass on an event click via the javascript? Thanks!
Posted by Dog | January 12, 2011 11:12 AM
Posted on January 12, 2011 11:12
Dog,
Yes it is possible, check the Phonegap google group for details, but it is pretty easy to do with a plugin or just a Javascript bridge which is what I did to interact with the Facebook SDK.
Posted by Dan Mayer | January 12, 2011 8:36 PM
Posted on January 12, 2011 20:36
Great post, I'm trying to create a new Activity inside of my Plugin that calls an Intent from another application. Phonegap keeps returning that the plugin called failed, do you know why?
Posted by Jason Teplitz | May 8, 2011 10:21 PM
Posted on May 8, 2011 22:21
You define your class as
public CustomJS(WebView view)
Yet you create a new object with
custom_js = new CustomJS();
Should that instead be
custom_js = new CustomJS(appView);
I'm not sure I'm a new Java programmer so I have to double check everything.
Thanks /Andy
Posted by AndyW | June 1, 2011 4:35 PM
Posted on June 1, 2011 16:35
Actually custom JS breaks using the old way on Android 2.3.x, I ended up converting most of my JS to Phonegap plugins. You might want to check here for those:
http://wiki.phonegap.com/w/page/36753494/How-to-Create-a-PhoneGap-Plugin-for-Android
Posted by Dan | June 4, 2011 10:17 AM
Posted on June 4, 2011 10:17