Passing a Javascript callback to Objective-C

Skip to first unread message

Ian Beck

Sep 8, 2010, 2:28:45 PM9/8/10
to JSCocoa
I'm having trouble passing a Javascript callback function to an
Objective-C method. Here's an example of the code that I'm running:

var callbackFunction = function(dictionary) {

var testCallback = function(objcObject) {

@implementation MyClass

// Loads up JSCocoa and calls the testCallback function:
// [jsc callJSFunctionNamed:@"testCallback" withArguments:self, nil];

- (void) invokeJSCallback:(JSValueRef)callbackFunction {
// Here's where I want to invoke the callbackFunction to send
control back to Javascript


Initially, I was getting all sorts of segfaults when I tried to do
anything with callbackFunction in Objective-C, so out of curiosity I
switched its type to "id", and sure enough I was getting an Obj-C
object rather than a JSValueRef as I'd expected. When I checked
[callbackFunction className] I got "NSCFDictionary", and when I tested
its contents it turns up empty.

What am I doing wrong? I can't figure out why I'm getting an empty
dictionary passed back instead of some form of reference to the
Javascript function that I passed in on the other side of the bridge.
Ideally what I want to do is convert the callbackFunction into a
JSValueRef so that I can do something like [jsc
callJSFunction:callbackFunction withArguments:args].

Thanks for any insight you can offer!


Patrick Geiller

Sep 8, 2010, 3:18:12 PM9/8/10

You can't use (JSValueRef) to move functions around as they are dependent on a specific context.
Instead, use (JSValueRefAndContextRef) - it's special cased to move raw JS values to ObjC.

- (void) invokeJSCallback:(JSValueRefAndContextRef)callbackFunction {
// Get JSCocoa controller from JSContextRef
id jsc = [JSCocoa controllerFromContext:valueAndContext.ctx];
// Call
[jsc callJSFunction:valueAndContext.value withArguments:[NSArray arrayWithObjects:..., nil]];


> --
> JSCocoa:
> Source:
> Docs:
> Group:
> Unsubscribe:

Ian Beck

Sep 8, 2010, 4:50:32 PM9/8/10
to JSCocoa
Thanks, Patrick! That was exactly the problem that I was having, and
it's now working perfectly.

Reply all
Reply to author
0 new messages