How does phoneGap (Cordova) work internally, iOS specific

2ndlife picture 2ndlife · Oct 12, 2012 · Viewed 9.3k times · Source

I have started developing html applications for mutliple platforms. I recently heard about Cordova 2.0(PhoneGap) and ever since I have been curious to know how the bridge works. After lot of code walking, i saw that the Exec.js is the code where call from JS -> Native happens

execXhr = execXhr || new XMLHttpRequest();
        // Changeing this to a GET will make the XHR reach the URIProtocol on 4.2.
        // For some reason it still doesn't work though...
        execXhr.open('HEAD', "file:///!gap_exec", true);
        execXhr.setRequestHeader('vc', cordova.iOSVCAddr);
        if (shouldBundleCommandJson()) {
            execXhr.setRequestHeader('cmds', nativecomm());
        }
        execXhr.send(null);
    } else {
        execIframe = execIframe || createExecIframe();
        execIframe.src = "gap://ready";

But want to understand how that works, what is the concept here, what does file:///!gap_exec or gap://ready do? and how does the call propgate to the lower layers (native code layers)

thanks a bunch in advance.

Answer

Christian Kuetbach picture Christian Kuetbach · Nov 9, 2012

The trick is easy:

There is a webview. This displays your app. The webview will handle all navigation events.

If the browser navigates to:

file:///!gap_exec 

or

gap://

the webview will cancel the navigation. Everything behind these strings is re-used as an identifier, to get the concrete plugin/plugin-method and parameter:

pseudo-url example:

gap://echoplugin/echothistext?Hello World

This will cause phonegap to look for an echoplugin and call the echothistext method to send the text "Hello World" to the (native) plugin.

update

The way back from native to javascript is (or may be) loading a javascript: url into the webview.

The concrete implementation is a little bit more complex, because the javascript has to send a callback-id to native code. There could be more than one native call are running at the same time. But in fact this is no magic at all. Just a number to get the correct JSON to the right javascript-callback.

There are different ways to communicate between the platform and javascript. For Android there are three or four different bridges.