Question

We use PhoneGap to use native capability of a mobile device. How does is work internally? How are we able to access PhoneGap's implementation classes from a JavaScript method? Can someone please explain this?

Was it helpful?

Solution

I did some spelunking on how Cordova iOS passes messages to the WebView. This is how to pass a message from iOS to JavaScript.

The UIWebView Class has a method called stringByEvaluatingJavaScriptFromString.

If you look in some files in the iOS Cordova Project, they are passing the JavaScript as a string that is to be executed to that function, e.g. CDVPlugin.m.

I do not know if iOS writes a new DOM node (something like <script>alert('from iOS');</script>) or it executes the JavaScript through a special hook in Safari. I believe the later, in that, the documentation referenced above says:

JavaScript execution time is limited to 10 seconds for each top-level entry point. If your script executes for more than 10 seconds, the web view stops executing the script. This is likely to occur at a random place in your code, so unintended consequences may result. This limit is imposed because JavaScript execution may cause the main thread to block, so when scripts are running, the user is not able to interact with the webpage.

JavaScript allocations are also limited to 10 MB. The web view raises an exception if you exceed this limit on the total memory allocation for JavaScript.

I don't know how they could actually impose those limitations without some special access to that UIWebView's internal state, so I doubt they are just inserting a new DOM node.

OTHER TIPS

I am not entirely sure, but here is the information tutorial. It is a good place to start.

The source code is openly available and thus can be examined to see how it is implemented, which is different on each platform thus you can't get a single answer that will cover all OSs. On iOS its done using a UIWebView, where native code can be invoked by forcing a browser location change using a proprietary url scheme. This change causes a method in the native code to be invoked which can examine the url scheme and passed parameters, then go off and do some relavant processing. Then there is a way of invoking Javascript from Objective-C within iOS that can be used to pass results back to the Javascript side of things.

The entire detailed process is too long to describe in an answer here.

How its implemented on other platforms is different, of course.

This mechanism can be abstracted away behind an API so that PhoneGap apps aren't aware of the differences in a specific platforms implementation detail.

Why not ask on the PhoneGap forum, or look at the source code if you require lots of details.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top