DShah
DShah

Reputation: 9876

How to execute JavaScript with JavaScriptCore framework?

I have implemented following code to execute JavaScript file of Jasmine Test Framework.

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;

This is my function which returns HTML data... When i am executing the script i am getting following error at Exception:

Exception = Can't find variable: jasmine

Though my script has declared jasmine variable at first line. What else could be the problem with above code???? Is their any other way to execute JavaScript??

One more question : Does JavaScriptCore framework supports DOM and other functionality of HTML??

Upvotes: 1

Views: 1863

Answers (1)

Cuper Hector
Cuper Hector

Reputation: 856

For your second question, JavaScriptCore doesn't support DOM and other HTML related stuff. It's a minimal engine which implements ECMA 262(?) specification. DOM support are implemented in WebCore which is a part of WebKit.

Go with PhantomJS if you want to do headless JavaScript/DOM tests

Upvotes: 2

Related Questions