使用JavaScriptCore调用Objective-C中的javascript函数

时间:2015-10-08 07:12:37

标签: objective-c javascriptcore

我有一个javascript代码(来自annevk/webvtt):

var WebVTTParser = function () {
    this.parse = function (input, mode) {
        ...
    }
};

在HTML中我称之为:

var pa = new WebVTTParser()
var r = pa.parse(input, mode)

现在我想在Objective-C中对此进行评估。我试过了:

[jsContext evaluateScript:script];

JSValue *parse = jsContext[@"WebVTTParser"][@"parse"];
NSLog("%@", [parse toString]); // undefined

JSValue *parsed = [parse callWithArguments:@[ input, mode ]];
NSLog("%@", [parsed toString]); // undefined

没有成功。 parse未定义,因此parsed也未定义。

如果我使用它:

JSValue *webVTTParser = jsContext[@"WebVTTParser"];
NSLog("%@", [webVTTParser toString]);

JSValue *parse = webVTTParser[@"parse"];
NSLog("%@", [parse toString]); // undefined

或者这个:

JSValue *webVTTParser = jsContext[@"WebVTTParser"];
NSLog("%@", [webVTTParser toString]);

JSValue *parserFunction = [webVTTParser callWithArguments:@[]]; // equivalent new WebVTTParser()?
NSLog(@"%@", [parserFunction toString]); // undefined

JSValue *parse = parserFunction[@"parse"];
NSLog("%@", [parse toString]); // undefined

然后在控制台日志中打印出webVTTParser,但其他所有内容仍未定义,因此我无法运行它。

如何从this.parse访问webVttParser功能?

1 个答案:

答案 0 :(得分:0)

好的,在阅读JSValue的源代码后,我找到了解决方法。

new WebVTTParser()

JSValue *webVTTParser = jsContext[@"WebVTTParser"];
JSValue *parser = [webVTTParser constructWithArguments:@[]];
来自Apple的

/*!
@method
@abstract Invoke a JSValue as a constructor.
@discussion This is equivalent to using the <code>new</code> syntax in JavaScript.
@param arguments The arguments to pass to the constructor.
@result The return value of the constructor call.
*/
- (JSValue *)constructWithArguments:(NSArray *)arguments;

并访问this.parse方法:

JSValue *parsed = [parser invokeMethod:@"parse" withArguments:@[ input, mode ]];

如:

/*!
@method
@abstract Invoke a method on a JSValue.
@discussion Accesses the property named <code>method</code> from this value and
            calls the resulting value as a function, passing this JSValue as the
            <code>this</code> value along with the specified arguments.
@param method The name of the method to be invoked.
@param arguments The arguments to pass to the method.
@result The return value of the method call.
*/
- (JSValue *)invokeMethod:(NSString *)method withArguments:(NSArray *)arguments;

但是因为我必须构造并调用几个方法,所以我在脚本中添加了自己的javascript函数,而不是那些复杂的Objective-C代码:

var parse = function(input, mode) {
    var pa = new WebVTTParser(),
        r = pa.parse(input, mode);
    ...
    return ...
};

并且只在Obj-C中调用此函数。