问题描述
我正在尝试从WebView中的JavaScript传递函数引用,因此异步Obj-C方法完成后,我的Objective-C代码可以调用然后再返回该函数。我看到了如何传递简单的类型-字符串,数字等-但似乎无法弄清楚如何传递函数引用,例如
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. I see how to pass in simple types -- strings, numbers, etc. -- but can't seem to figure out how to pass something a function reference, like
window.myRootObject.myObjCSelector("some-string", function(data) {
console.log(data);
});
我已经在Google周围搜索,但仍然很简短,并且没有找到在文档中(尚未)。在Cocoa工作,但希望能够在iOS上做同样的事情。
I've Googled around, but continue to come up short, and haven't found a reference to this in the docs (yet). Working in Cocoa, but would love to be able to do the same sort of thing on iOS.
在此先感谢您的帮助!
编辑:函数参数应该是匿名的-希望可以弄清楚。 :)
The function argument should be anonymous -- hopefully this clarifies. :)
推荐答案
最后弄清楚了这一点。也许有更好的方法(如果是,请发出提示!),但以下方法似乎可行。在我的Obj-C( NSObject
派生)类中-向其中传递对 WebView
的引用-我定义了以下脚本可访问的方法:
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);
}
实际上,它也可以通过Objective-C块异步运行,但是要点以上。希望它对其他人有帮助!
This actually works asynchronously as well, through Objective-C blocks, but the gist is above. Hope it helps someone else!
这篇关于如何将JavaScript回调函数传递给Cocoa / Obj-C?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!