Return values ​​to JavaScript when calling an Objective-C function


I've been using WebViewJavascriptBridge to bridge Objective-C and JavaScript in an iOS application. It works great but it lacks support for returning values to the calling JavaScript code from the called native Objective-C function.

I'm pretty sure that Cordova (PhoneGap) does that in some way with callbacks but I've been having a hard time trying to understand how the underlying mechanics work.

Is there anyone who's had the same problem and that managed to find a solution?

If you mean, "return" in the sense that your JS caller will see the results as returned from the call, I don't know how to do it. I suspect it would take a level of thread manipulation not available in JS. Instead, you can recode your JS side logic to create a result handler function. In pseudo code:

res = CallObjC(args);
work with res...


CallObjC(args, function(res) { work with res...});

Admittedly a bit awkward but get used to it - it is a very common pattern. Internally, the JS bridge code creates a mapping of the request to the callback function. When the ObjC code has the result, it uses WebView's stringByEvaluatingJavaScriptFromString to call the JS bridge code that locates and invokes the callback.

@Richard - Be a bit careful with the solution you posted. Setting window.location to invoke shouldStartLoadWithRequest can result in both lost functionality in the webview and also lost messages to ObjectiveC. Current practice is to use an iframe and have some kind of message queue that can buffer up messages.