Wednesday 7 May 2014

Execute Javascript in iOS Applications [ iOS 7 ]

-(void) evaluateJavscript
{
    NSString * jsCode = @"1+2";
    JSContext *context = [[JSContext alloc] init];
    JSValue * value = [context evaluateScript:jsCode];
    NSLog(@"Output = %d", [value toInt32]);

}
-(void) accessJavscriptVariables
{
    JSContext *context = [[JSContext alloc] init];
    NSString * jsCode = @"var x; x=10;";
    [context evaluateScript:jsCode];

    JSValue * a =context[@"x"];
    NSLog(@"x = %d", [a toInt32]);
}
-(void) accessJavscriptFunctions
{
    //function with arguments
    JSContext *context = [[JSContext alloc] init];
    NSString * jsCode = @"function sum(a,b) { return a+b;} ";
    [context evaluateScript:jsCode];

    JSValue * func =context[@"sum"];
    NSArray * args = @[[NSNumber numberWithInt:10],[NSNumber numberWithInt:20]];
    JSValue * ret =[func callWithArguments:args];
    NSLog(@"10+20 = %d", [ret toInt32]);

    //function without arguments
    NSString * jsCode2 = @"function getRandom() { return parseInt(Math.floor((Math.random()*100)+1));} ";
    [context evaluateScript:jsCode2];

    JSValue * func2 =context[@"getRandom"];

    for(int i=0;i<5;i++)
    {
        JSValue * ret2 =[func2 callWithArguments:nil];
        NSLog(@"Random Value = %d", [ret2 toInt32]);
    }
}
-(void) codeBlocks
{
    JSContext *context = [[JSContext alloc] init];

    //we are telling that "sum" is function, takes two arguments
    context[@"sum"] = ^(int arg1,int arg2)
    {
        return arg1+arg2;
    };

    NSString * jsCode =@"sum(4,5);";
    JSValue * sumVal = [context evaluateScript:jsCode];

    NSLog(@"Sum(4,5) = %d", [sumVal toInt32]);


    //we are telling that "getRandom" is function, does not take any arguments
    context[@"getRandom"] = ^()
    {
        return rand()%100;
    };

    NSString * jsCode2 =@"getRandom();";
    for(int i=0;i<5;i++)
    {
        JSValue * sumVal2 = [context evaluateScript:jsCode2];
        NSLog(@"Random Number = %d", [sumVal2 toInt32]);
    }
}
-(void) jsExportProtocol
{
    JSContext * context = [[JSContext alloc] init];
    NSString * jsCode = @"function sqrtOf(obj){ return MyObject.getSqure(obj);}";

    //adding Objective-C Class to Javascript.
    context[@"MyObject"]=[MyObject class];

    [context evaluateScript:jsCode];

    MyObject * obj =[MyObject new];
    obj.x =10;

    JSValue * func =context[@"sqrtOf"];
    JSValue * val = [func callWithArguments:@[obj]];

    //we got MyObject from javascript.
    MyObject *sqrtObj = [val toObject];

    NSLog(@"Value =%d, %d", obj.x, [sqrtObj getX]);
}

Calling a javascript function located in a WebView

JSContext *context = [theWebView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];

No comments:

Post a Comment