I\'m trying to pass a function reference from JavaScript in a WebView, so my Objective-C code can call then back into that function when the asynchronous Obj-C method completes.
Finally figured this out. There might be a better way (and if so, please chime in!) but the following seems to work. In my Obj-C (NSObject
-derived) class -- into which I pass a reference to a WebView
-- I define the following script-accessible method:
#import <WebKit/WebKit.h>
#import <JavaScriptCore/JavaScriptCore.h>
- (void) search:(NSString *)prefix withCallback:(WebScriptObject *)callback;
... which is intended to take two arguments: a string to search with, and an anonymous function callback to handle the result. It's implemented thusly:
- (void) search:(NSString *)prefix withCallback:(WebScriptObject *)callback
{
// Functions get passed in as WebScriptObjects, which give you access to the function as a JSObject
JSObjectRef ref = [callback JSObject];
// Through WebView, you can get to the JS globalContext
JSContextRef ctx = [[view mainFrame] globalContext];
// In my case, I have a JSON string I want to pass back into the page as a JavaScript object
JSValueRef obj = JSValueMakeFromJSONString(ctx, JSStringCreateWithCFString((__bridge CFStringRef)responseString));
// And here's where I call the callback and pass in the JS object
JSObjectCallAsFunction(ctx, ref, NULL, 1, &obj, NULL);
}
This actually works asynchronously as well, through Objective-C blocks, but the gist is above. Hope it helps someone else!
Maybe if it's a global non-anonymous function you can try passing the function name to Obj-C and then evaluating sth like [NSString stringWithFormat:@"%@()", function_name]
?