How does phoneGap (Cordova) work internally, iOS specific

假装没事ソ 提交于 2019-12-03 16:56:13

问题


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.


回答1:


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.




回答2:


I am trying to figure this out in more detail, too. Basically there are 2 Methods on the iOS side that can help ...

  • - webView:shouldStartLoadWithRequest:navigationType: and
  • - stringByEvaluatingJavaScriptFromString:script

From the sources it seems cordova sends a "READY" message using webView:shouldStartLoadWithRequest:... and then picks up results with the second message, but I am not sure.

Cordova Sources iOSExec

There is much to learn there.



来源:https://stackoverflow.com/questions/12857462/how-does-phonegap-cordova-work-internally-ios-specific

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!