Apple introduced JavaScriptCore.framework with iOS 7 SDK, before that there was only one function -stringByEvaluatingJavaScriptFromString: available on UIWebView to execute JavaScript in iOS via Web Views.

Ways to execute JavaScript in iOS

  1. Writing JavaScript code in Objective C code.
  2. Using .js file for reuse purpose / for difficult to port code in Objective C
  3. Web views using JavaScript

#1. JavaScript code in Objective C

import JavaScriptCore framework

#import <JavaScriptCore/JavaScriptCore.h>

You are going to use two important Classes from this framework

 JSContext

JSContext represents a JavaScript execution environment.  JavaScript execution takes place within a context. You provide your JavaScript code in the form of NSString for execution.

JSValue

A JSValue is a reference to a value within the JavaScript object space of a JSVirtualMachine. All instances of JSValue originate from a JSContext and hold a strong reference to this JSContext. JSValue holds JavaScript values, variable and functions you can convert these to Objective C type data by using function available on JSValue. E.g toString, toArray, toBool etc. 

Example

Simple sum calculation

NSString * jsCode = @"2+3";
JSContext *context = [[JSContext alloc] init];
JSValue * value = [context evaluateScript:jsCode];
NSLog(@"SUM = %d", [value toInt32]);

#2. Using .js file in Objective C

Example

Create file Demo.js with following content, and add it in project.

function HelloJS(name) 
{
   return "Hello, " + name + "!";
}

Now write following code to invoke HelloJS function from Demo.js in objective c code.

//Get JS file content in string format
NSString *path = [[NSBundle mainBundle] pathForResource:@"Demo" ofType:@"js"];
NSString *jsScript = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
 
//Initialize context with script
JSContext *context = [[JSContext alloc] init];
[context evaluateScript: jsScript];
 
//Set function name to invoke
JSValue *function = context[@"HelloJS"];
 
//Call fuction with parameter
JSValue* result = [function callWithArguments:@[@"World"]];
 
NSLog(@"Output : %@",[result toString]);

#3. Web views using JavaScript

  1. Load your file into web view.
  2. Set delegate of web view to self.
  3. When web view finishes loading call methods in your js

Example

- (void) webViewDidFinishLoad:(UIWebView *)webView
{
    //Execute javascript method 
    [_webView stringByEvaluatingJavaScriptFromString:@"methodName();"];
}
Advertisements