How can I pass a JavaScript callback function to Cocoa/Obj-C?

前端 未结 2 1280
予麋鹿
予麋鹿 2021-02-03 15:31

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.

相关标签:
2条回答
  • 2021-02-03 16:15

    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!

    0 讨论(0)
  • 2021-02-03 16:21

    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] ?

    0 讨论(0)
提交回复
热议问题