终于想通了。可能有更好的方法(如果是这样,请加入!)但以下方法似乎有效。在我的 Obj-C ( NSObject
-derived) 类中——我将一个引用传递到其中WebView
——我定义了以下脚本可访问的方法:
#import <WebKit/WebKit.h>
#import <JavaScriptCore/JavaScriptCore.h>
- (void) search:(NSString *)prefix withCallback:(WebScriptObject *)callback;
...它旨在采用两个参数:一个用于搜索的字符串和一个用于处理结果的匿名函数回调。它是这样实现的:
- (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);
}
这实际上也可以通过 Objective-C 块异步工作,但要点在上面。希望它可以帮助别人!