Main

javascript Archives

July 10, 2010

Adding Custom JavaScript Handlers for PhoneGap Android

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.

June 26, 2010

Javascript document.addEventListener PhoneGap deviceready issues

I had some issues with the deviceready callback. I had seen some similar posts, and figured I could save someone some time. Basically when using document.addEventListener order matters a lot. It all comes down to exactly when this line is loaded and what is already defined.

document.addEventListener("deviceready", deviceSetup, true);

We have custom JS, and originally it was loaded second, so the
deviceready event was fired before, the listener was set.

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

After that I was still having an issue and it turns out the method you
define register as the callback needs to be defined before you add the
listener.
So having this in our lscustom.js works.

var deviceSetup = function(){ 
  console.log("Device Setup"); 
}; 

document.addEventListener("deviceready", deviceSetup, true);
While, the below fails.
document.addEventListener("deviceready", deviceSetup, true);
var deviceSetup = function(){
console.log("Device Setup");
};

Anyways since I ended up wasting a bit of time searching and debugging this issue, I figured I would share my debugging session.

Web 2.0 craziness

View Dan Mayer's profile on LinkedIn


I Power Seekler
I Power Seekler

www.flickr.com
This is a Flickr badge showing public photos and videos from mayer_dan. Make your own badge here.

Creative Commons License
This weblog is licensed under a Creative Commons License.