PhoneGap Native Bridge
The “native bridge” is the secret sauce of PhoneGap and is what allows JavaScript in an embedded browser talk to native code and vice-versa.
On every platform we do this differently depending on what features that native browser has. Here is the list of platforms and how we do it.
iOS: To communicate from JavaScript to native we call window.location = “gap://Class.method/args” and then intercept the url in native code and parse our the parameters. The class / method is then dynamically loaded / called. To call JavaScript from native we use UIWebView.stringByEvaluatingJavaScriptFromString.
Android: Communication from JavaScript to native is achieved by overriding the JavaScript prompt function in the Android native code and the message passed is much like that used in iOS. We used to use WebView.addJavascriptInterface to add Java objects directly to the JavaScript sandbox but that was causing some devices to crash with Android 2.3. To call JavaScript from native we currently use WebView.loadUrl(”javascript:…”) but that has some problems so we are soon moving over to polling a Java message queue calling a local HTTP server via a long-lived XHR connection.
BlackBerry 4.x: document.cookie is the only way to talk between JavaScript and native. JavaScript sets the cookie for native to read and JavaScript polls the cookie for messages from native. Fucking elegant!
BlackBerry WebWorks: Astoundingly the new BlackBerry WebWorks SDK is pretty damn nice. You can expose Java objects to JavaScript with ScriptEngine.addExtension and you can call JavaScript from native with ScriptEngine.executeScript. The context for the JavaScript execution can even be specified. Seriously great work there.
Qt: This one is not quite ready but it will use the QWebFrame.addToJavaScriptWindowObject to expose native objects to JavaScript and will likely use polling of those exposed native objects to get data back into JavaScript - much like the Android approach
Windows Phone 7: There is something called window.external.Notify in the browser (mapped to a native object through the ScriptNotify event) on Windows Phone 7 that we use to send messages into native code. Going the other way there is WebBrowser.InvokeScript.
webOS, WRT: The platforms that are just JavaScript don’t have any native code. Well, we might look into the native side of webOS one day but no time soon.