Tricks for Debugging PhoneGap Applications in Desktop Browsers

I often encourage people to develop as much as possible in desktop browsers when they are building PhoneGap applications.  While there are remote debugging tools such as weinre for remote debugging on devices, the developer experience is still better inside of a desktop browser because it gives you breakpoints and memory inspection capabilities.  In most cases, you can develop the vast majority of your application within the desktop browser, and switch to a physical device when integrating with PhoneGap APIs or for performance testing. Personally, I use Chrome, and take advantage of the Chrome Developer Tools.

However, when developing from the local file system, you will run into a few roadblocks with desktop browsers.  A big issue is the browser security model.  If you try to asynchronusly request files when the application is loaded from the local file system, you’ll like get an error like:

XMLHttpRequest cannot load (filename or url). Origin null is not allowed by Access-Control-Allow-Origin.

Luckily, there are a few tricks you can use to get around this… local HTTP servers and relaxing the browser’s security.  Note: I’m on a Mac, and I don’t know the syntax for these on Windows.

Local HTTP Server

The first option is to use a local web server to host files.   You can fire up a simple HTTP server from any directory in OSX by opening a terminal and using the following command:

python -m SimpleHTTPServer 8000

An HTTP server will start, and you’ll be able to access any content from that directory and child directories from the URL http://localhost:8000/  Thanks to @mesh for this trick.

However, this will only work for static content that is within your directory structure.   If you need dynamic content, you’ll need some sort of application server infrastructure.

Relaxed Browser Security

OK, that’s great, but it doesn’t cover every situation.   What if you don’t want a local application server configuration?  What if you want to develop against services that are remote, and you don’t control them?    Well, you are in luck.

You can disable security restrictions in Chrome to allow you to access these services.   The following command will allow unrestricted access from the file system, and will also allow cross-site requests.   Kill Chrome, then relaunch from a terminal window with the following flags:

open -a /Applications/Google\ Chrome.app --args --allow-file-access-from-files --disable-web-security

Using this configuration, you’ll be able to open an HTML file from the local file system, and that file will be able to make requests to other sites to access data or other resources.

In the screenshot below, you can see that I launched my Census Browser application from the local file system, and it can access services from http://www.tricedesigns.com.   With the default browser security policy, this would not be possible.

Local Application Debugging With Remote Services

WARNING: ONLY USE THIS FOR DEBUGGING!

Do not use this configuration for normal web browsing because it will leave your browser security wide open, and able to be exploited and compromised.  Do not browse the web when you’ve relaxed the security policy.

Thanks to fellow Adobe evangelist Piotr Walczyszyn for introducing me to this trick.

Pushing Data to a PhoneGap Web View

UPDATE:

In PhoneGap 1.5, the naming conventions were changed to use the Apache Cordova naming conventions.   EX: PGPlugin is now CDVPlugin, phonegap.js is now cordova.js, etc…   If you are running into issues, please be sure to check the PhoneGap version and appropriate naming conventions.

ORIGINAL POST:

In my last post, which gave a crash course in PhoneGap Native Plugins, I discussed a scenario where you could use a native plugin and the writeJavascript function to “push” data into the UI/web view layer from the native code layer.   To elaborate on this scenario, I put together a sample application that demonstrates this concept in action.

I set up the sample application so that there is an extremely basic HTML user interface.   In that user interface, you can click a link which executes native code to start a timer (in the native code layer).   Once the timer is started, the user interface will be updated with a “started” message, and on every timer event, the user interface will be updated with the current time, as it is provided by the native code layer.   In this case, I am using a timer to simulate an external thread of execution, or stream of input from some other source (device or stream).   Take a look at the video below to see it in action:

Next, let’s examine how it works.

The HTML interface is very simple.   There is an <a> link, which calls the “doStart()” JavaScript function, an <h4> element to display status, and an <h2> element to display the content received from the native code layer. When the “doStart()” function is invoked, it calls the SamplePlugin JavaScript class’ “start()” function, passing a reference to the “successCallback()” function, which will get executed when a callback is received from the native layer.   The “updateContent()” function will just set the innerHTML value of the “output” element to the value passed as a parameter.

[html]<!DOCTYPE html>
<html>
<head>
<title></title>

<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no;" />
<meta charset="utf-8">

<script type="text/javascript" charset="utf-8" src="phonegap-1.4.1.js"></script>
<script type="text/javascript" charset="utf-8" src="SamplePlugin.js"></script>
<script type="text/javascript">

function doStart() {
SamplePlugin.start( successCallback );
}

function successCallback() {
document.getElementById( "status" ).innerHTML = "started";
}

function updateContent( data ) {

document.getElementById( "output" ).innerHTML = data;
}

</script>
</head>
<body onload="onBodyLoad()">
<h1>Hey, it’s PhoneGap!</h1>
<a href="javascript:doStart()">Start!</a>

<h4 id="status"></h4>
<h2 id="output"></h2>
</body>
</html>[/html]

In the SamplePlugin.js file, which is the JavaScript component of the native plugin, you can see that there is a SamplePlugin class instance that has a “start()” function.   The “start()” function invokes the PhoneGap.exec() command to invoke native code.

[js]var SamplePlugin = {
start: function (success, fail) {
return PhoneGap.exec(success, fail, "SamplePlugin", "start", []);
}
};[/js]

In the native code, there is a basic class that extends the PGPlugin class.  When the user invokes the “start()” function in JavaScript, the native “start” function will be invoked.   In this function, output is appended to the console using NSLog, and a NSTimer instance is started.   Once the timer is started, a success callback will be sent back to the HTML/JavaScript layer.

Now, the timer is executing indefinitely in the native code.   You will notice that in the timer handler “onTick” function, a message is written to the console, and a JavaScript string is created and routed to the UI layer using writeJavascript.   In this case, the JavaScript string just contains the current date as a string, to maintain simplicity.

[objc]#import "SamplePlugin.h"

@implementation SamplePlugin

– (void) start:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options {

NSString* callbackID = [arguments pop];
NSLog(@"start invoked");

[NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:@selector(onTick:)
userInfo:nil
repeats:YES];

PluginResult* pluginResult = [PluginResult resultWithStatus:PGCommandStatus_OK messageAsString: @"OK"];
[self writeJavascript: [pluginResult toSuccessCallbackString:callbackID]];
}

-(void)onTick:(NSTimer *)timer {

NSLog(@"timer tick!");

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"dd-MM-yyyy HH:mm:ss"];

NSString *dateString = [formatter stringFromDate:[NSDate date]];
NSString *js = [NSString stringWithFormat:@"updateContent( ‘%@’ );", dateString];

[self writeJavascript:js];
}

@end[/objc]

When the native-generated JavaScript is executed, it will invoke the updateContent() JavaScript function, which will then update the HTML user interface.

While this example is extremely basic, you could use this exact same approach to push more complex data to the UI layer in real time.  This data could be coming from network activity, Bluetooth connections, or physical devices that are connected to the mobile device.

You can download the full source code for this sample project directly from: PhoneGapPluginDataPush.zip

PhoneGap Native Plugins

UPDATE:

In PhoneGap 1.5, the naming conventions were changed to use the Apache Cordova naming conventions.   EX: PGPlugin is now CDVPlugin, phonegap.js is now cordova.js, etc…   If you are running into issues, please be sure to check the PhoneGap version and appropriate naming conventions.

ORIGINAL POST:

Last night I attended a great Baltimore JavaScript Users Group meetup to engage with the community and to speak about PhoneGap native plugins. Many thanks to @bmorejs for having me, and great job to my fellow presenters Mike Wolf, who presented “PhoneGap: Blood and Guts” and Mike McKay, who presented on PhoneGap + CouchDB.

As promised, here are my slides, and I’ll also try to provide a bit more detail since there isn’t much of an explanation within the slide content: PhoneGap Native Plugins.pdf

PhoneGap Native Plugins Presentation

Here’s a brief synopsis of my presentation…

PhoneGap allows you to create natively installed mobile applications using web technologies (HTML, JS, CSS).  PhoneGap provides an API that lets you access capabilities of the native device/underlying operating system.  “Out of the box”, PhoneGap provides APIs for Accelerometer, Camera, Compass, Media, FileSystem, etc…  (You can get more info about the PhoneGap API from docs.phonegap.com.)

However, PhoneGap does not attempt to recreate every native API.   Luckily, if you need to access native functionality that isn’t already exposed, then you can easily create a native plugin to provide access to that native functionality.   For example, low latency audio processing, multi-screen iOS experiences, or anything else that has a native API.

PhoneGap native plugins shouldn’t be thought of as “plugins” like Flash Player inside of a browser, rather you are “plugging in” additional functionality that extends the core PhoneGap framework.   Even the PhoneGap core API itself is built upon this plugin model.  If you examine PhoneGap.plist in an iOS project, or phonegap.xml in an Android project, you can easily see the API mappings to native classes.

All PhoneGap plugins consist of a JavaScript class that exposes your functionality to your HTML/JS applications (red box in figure below).   The JavaScript class (green box in figure below) communicates to the native layer through the core PhoneGap class using PhoneGap.exec().  This invokes native functionality in your native plugin  (purple box in figure below).

Original image source: wiki.phonegap.com

You develop your JavaScript class to mirror the API of the native class.   In the JavaScript class, you invoke the native function using PhoneGap.exec, as shown below:

PhoneGap.exec(success, fail,   ”NameOfClassMapping”,   ”nameOfFunction", [params]);

Where “success” is a reference to a JavaScript function that will be invoked upon a “success” callback from the native code,  “fail” is a reference to a JavaScript function that will be invoked upon a “fail/error” callback from the native code, “NameOfClassMapping” is the plugin class reference (from phonegap.plist or phonegap.xml), “nameOfFunction” is the name of the native function that should be invoked, and [params] is an array of parameters to be passed into the native function.

In both Android and iOS, native plugin classes extend the PGPlugin class.

iOS

In iOS applications, this function is invoked directly, so invoking a function “myFunction” on the class “MyPlugin” is basically the same as calling the Objective C syntax:

[objc][MyPlugin myFunction];[/objc]

In iOS applications, you “return” a result to the web view using the writeJavascript method of the PGPlugin class, which invokes a JavaScript string inside of the web view. You create a PluginResult class instance, and write the JavaScript string back to the web view:

[objc]PluginResult* pluginResult = [PluginResult resultWithStatus:PGCommandStatus_OK messageAsString: @"OK"];
[self writeJavascript: [pluginResult toSuccessCallbackString:callbackID]];[/objc]

You can also write native-code-generated JavaScript strings back to the PhoneGap web view using the writeJavaScript method – you can use this to “push” data or instructions to the web view at any time without being requested. An example of this is below:

[objc]NSString *js = [NSString stringWithFormat:@"myJSFunction( ‘%@’ );" val];
[self writeJavascript:js];[/objc]

In the web view, this would invoke the “myJSFunction” JavaScript function with the parameter in the “val” variable.

Android

In Android applications, functions are not invoked directly, instead, the “execute” method of the PGPlugin class in executed.  Inside of your class, you override the “execute” method, and determine the behavior based upon the “action” parameter, as shown below:

[java]public PluginResult execute(String action,   JSONArray data, String callbackId){
//do something based upon "action"
if ( action.equals( "foo" ) ) {
//handle the "foo" action
}
else if ( action.equals( "myFunction" ) ) {
//handle the "myFunction" action
}
result = new PluginResult(Status.OK);
return result;
}[/java]

When you return the PluginResult class at the end of this function, that PluginResult will be evaluated to call back to the success or error handler function.

You can also communicate back to the PhoneGap web view using the PGPlugin sendJavascript function to invoke custom JavaScript at any time, just as I described the iOS writeJavascript function above:

[java]this.sendJavascript( myJavaScriptString )[/java]

It is important to understand that regardless of iOS, Android, or any other platform, communication between the web view JavaScript and the native code layer is not synchronous. Do not expect that your native code has executed in sequence after you have requested a native command. You need to use the success/error callback paradigm, and build your application logic using asynchronous coding practices.

Also keep in mind that writeJavascript or sendJavascript can be invoked at any time, not just after a method has been invoked by the JavaScript interface. Using sendJavascript and writeJavascript can enable you to “push” data to the web view. For example, let’s say you are monitoring a specific piece of hardware attached to a mobile device … perhaps a heart rate monitor. You could have a native heart rate monitor class that communicates with the device in a separate thread, and it pushes data back to the JavaScript layer in real time.

You can read more specifics about native plugins at http://wiki.phonegap.com

You can read more about the native plugin examples from last night’s presentation at the links below. Both are fully open source and free.

You can also browse the existing collection of open source native plugins at:

Update: You can also see a sample scenario for pushing data from a native plugin to the UI layer at:

Enjoy!