Send javascript function to objective-C using JavascriptCore

I am trying to send a Javascript to Objective-C function object via JavascriptCore using the JSExport protocol. I have a function declared in Objective-C corresponding to JSExport as follows:

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

      

After declaring this class, I am trying to call the function above using the 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 passed to my Objective-C method is of type "NSDictionary", which doesn't seem very valuable if what I wanted to do was call this function from Objective-C at a later point in time. Is this possible with JavascriptCore?

+3


source to share


2 answers


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

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

      



The parameter declaration (id)func

seems to cause the javascript-cocoa bridge to convert it to an NSDictionary (as you noticed), making it unusable as a callable JSValue.

+1


source


This is definitely possible, but you need to change newWithFunc to accept a JSValue * and not a simple identifier. The reason is that JSValue * is a special type for JavaScriptCore - it will not try to convert the JS value to its own equivalent, but rather wrap it in JSValue and pass it.



+1


source







All Articles