【问题标题】:How to execute JavaScript with JavaScriptCore framework?如何使用 JavaScriptCore 框架执行 JavaScript?
【发布时间】:2012-01-10 05:29:16
【问题描述】:

我已经实现了以下代码来执行 Jasmine Test Framework 的 JavaScript 文件。

NSMutableArray * fArr = [[NSBundle mainBundle] pathsForResourcesOfType:@"js" inDirectory:@"scripts/JS_TestFramework/lib/jasmine-1.1.0"];
NSMutableString *fullFrameworkScript = nil;
    NSString *script;

    for (int i = fArr.count-1; i >= 0; i--) 
    {
        NSMutableString* filePath = [fArr objectAtIndex:i];

        fullFrameworkScript = [NSMutableString string];

        NSError*    error;

        script = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];

        if(script)
        {
            [fullFrameworkScript appendString:script];
        }
    }
    JSValueRef result;
if(fullFrameworkScript)
    {
        JSStringRef scriptJS = JSStringCreateWithCFString(fullFrameworkScript);

        JSValueRef exception = NULL;

        result = JSEvaluateScript(context, scriptJS, NULL, NULL, 1, &exception);

        if(exception)
        {
            [self logException:exception];
            exception = NULL;
        }

        JSStringRelease(scriptJS);
    }

JSStringRef step1 = JSStringCreateWithCFString(@"jasmine.getEnv().addReporter(new jasmine.TrivialReporter())");

JSValueRef exception = NULL;

    JSObjectRef fn          = JSObjectMakeFunction(context, step1, 0, NULL, JSStringCreateWithCFString(script), NULL, 0, NULL);
    result      = JSObjectCallAsFunction(context, fn, NULL, 0, NULL, &exception);

    if(exception)
    {
        [self logException:exception];
        exception = NULL;
    }

    JSStringRelease(step1);

    [MTPScriptExecutionContext removeAllObjects];

    JSStringRef htmlResult = JSValueToStringCopy(context, result, NULL);

    NSString *htmlData = [NSMakeCollectable(JSStringCopyCFString(kCFAllocatorDefault, htmlResult)) autorelease];

    JSStringRelease(htmlResult);

    return htmlData;

这是我的函数,它返回 HTML 数据...当我执行脚本时,出现以下异常错误:

Exception = Can't find variable: jasmine

虽然我的脚本在第一行声明了jasmine 变量。上面的代码还有什么问题???他们还有其他执行 JavaScript 的方式吗??

还有一个问题:JavaScriptCore 框架是否支持 DOM 和 HTML 的其他功能??

【问题讨论】:

    标签: javascript iphone objective-c jasmine javascriptcore


    【解决方案1】:

    对于第二个问题,JavaScriptCore 不支持 DOM 和其他与 HTML 相关的东西。它是一个实现 ECMA 262(?) 规范的最小引擎。 DOM 支持在 WebCore 中实现,它是 WebKit 的一部分。

    如果您想进行无头 JavaScript/DOM 测试,请使用 PhantomJS

    【讨论】:

      猜你喜欢
      • 2011-08-14
      • 2011-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-14
      • 2015-02-18
      • 1970-01-01
      相关资源
      最近更新 更多