3

I'm trying to send a Javascript function object to Objective-C via JavascriptCore, leveraging the JSExport protocol. I have a function declared in Objective-C, conforming to JSExport as follows:

(class View)
+ (void) newWithFunc:(id)func
{
    NSLog(@" %@ ", func);   
}

After declaring this class, I try to call the function above with a Javascript function object as a parameter

JSValue *val;
val = [context evaluateScript:@"var mufunc = function() { self.value = 10; };"];
val = [context evaluateScript:@"mufunc;"];
NSLog(@" %@", val); //Prints as 'function() { self.value = 10; }', seems correct.
val = [context evaluateScript:@"var view = View.newWithFunc(mufunc);"];

When the last call is made, the parameter sent to my Objective-C method is of type 'NSDictionary', which doesn't seem very valuable if what I would like to do is call that function from Objective-C at a later point in time. Is this possible with JavascriptCore?

2 Answers 2

1

Please mark Tayschrenn's answer as correct. I don't know how he knew this or where it's documented, but this is what I figured out by trial and error:

- (void)newWithFunc: (JSValue*)func
{
    [func callWithArguments:@[]]; // will invoke js func with no params
}

Declaring the parameter (id)func apparently causes the javascript-cocoa bridge to convert it to an NSDictionary (as you noticed), rendering it unusable as a callable JSValue.

Sign up to request clarification or add additional context in comments.

Comments

1

This is definitely possible, but you need to change newWithFunc: to accept a JSValue* rather than plain id. The reason is that JSValue* is a special type for JavaScriptCore - it won't try to convert the JS value to its native equivalent but rather wrap it in a JSValue and pass it on.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.