In this tutorial, I have covered How to execute JavaScript in iOS / Objective-C. You can execute JavaScript in iOS applications with the help of JavaScriptCore.framework. This framework is supported in iOS7 & OSX 10.9

List of features supported by Javascript.framework
a) Evaluate JavaScript code in Objective-C
b) Access JavaScript Variables in Objective-C
c) Access JavaScript functions and execute them in Objective-C
d) Execute Objective-C code from JavaScript
e) Export Objective-C classes and use them in JavaScript.

Download the source code: 

To access JavaScript framework, you need to include the header file

1
#import <JavaScriptCore/JavaScriptCore.h>

List of Main Classes supported by framework:
JSContext : For any javascript operations you need JSContext.

1
JSContext *context = [[JSContext alloc] init];

JSValue : JSValue holds JavaScript values,variables and functions. List of main methods in JSValue.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// Convert this value to a corresponding Objective-C object, according to the
// conversion specified above.
- (id)toObject;
 
// Convert this value to a corresponding Objective-C object, if the result is
// not of the specified class then nil will be returned.
- (id)toObjectOfClass:(Class)expectedClass;
 
// The value is copied to a boolean according to the conversion specified by the
// JavaScript language.
- (BOOL)toBool;
 
// The value is copied to a number according to the conversion specified by the
// JavaScript language.
- (double)toDouble;
 
// The value is copied to an integer according to the conversion specified by
// the JavaScript language.
- (int32_t)toInt32;
 
// The value is copied to an integer according to the conversion specified by
// the JavaScript language.
- (uint32_t)toUInt32;
 
// If the value is a boolean, a NSNumber value of @YES or @NO will be returned.
// For all other types the value will be copied to a number according to the
// conversion specified by the JavaScript language.
- (NSNumber *)toNumber;
 
// The value is copied to a string according to the conversion specified by the
// JavaScript language.
- (NSString *)toString;
 
// The value is converted to a number representing a time interval since 1970,
// and a new NSDate instance is returned.
- (NSDate *)toDate;
 
// If the value is null or undefined then nil is returned.
// If the value is not an object then a JavaScript TypeError will be thrown.
// The property "length" is read from the object, converted to an unsigned
// integer, and an NSArray of this size is allocated. Properties corresponding
// to indicies within the array bounds will be copied to the array, with
// Objective-C objects converted to equivalent JSValues as specified.
- (NSArray *)toArray;
 
// If the value is null or undefined then nil is returned.
// If the value is not an object then a JavaScript TypeError will be thrown.
// All enumerable properties of the object are copied to the dictionary, with
// Objective-C objects converted to equivalent JSValues as specified.
- (NSDictionary *)toDictionary;

Accessing Javascript Code in Objective-C

1).Evaluating Javascript Code

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

2).Access Javascript Variables. Variables and functions are accessed from JSContext.
To access varible from Javascript : context[@"x"]
To access function from javascript : context[@"myfun"]

1
2
3
4
5
6
JSContext *context = [[JSContext alloc] init];
    NSString * jsCode = @"var x; x=10;";
    [context evaluateScript:jsCode];
 
    JSValue * a =context[@"x"];
    NSLog(@"x = %d", [a toInt32]);

3).Access Javascript functions and execute them in Objective-C

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//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]);
    }

Call Objective-C code from JavaScript

Objective-C code is called from JavaScript in two ways

1.CODE BLOCKS

Objective-C code block can be called from JavaScript.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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]);
    }

2.USING JSEXPORT PROTOCOL

You can see the comparison between Objective-C Object and it’s equivalent Javascript Object below.

1
2
3
4
5
6
7
8
9
10
11
12
@interface MyObject
@property  int x;
 
-(int) getX;
+(MyObject *) getSqure:(MyObject*)obj;
 
@end
 
//Usage:
MyObject * obj = [MyObject new];
[obj getX];
[MyObject getSqure:obj];
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
function MyObject()
{
    //member variable
    this.x=0;
 
    //instance method
    this.getX = function()
                    {
                    return this.x;
                    }
}
 
//static method
MyObject.getSqure = function(obj)
{
    var newObj = new MyObject();
    newObj.x = obj.x * obj.x;
    return newObj;
}
 
//Usage:
var obj = new MyObject();
obj.x=10;
var sqrObj = MyObject.getSqure(obj);

To make Javascript interacting with Objective-C Object, We need to have a Protocol which should be inherited
from JSExport. Move all the variables and functions to prototype to access them in JavaScript.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
@protocol MyObjectExport
@property  int x;
 
-(int) getX;
+(MyObject *) getSqure:(MyObject*)obj;
 
@end
 
@interface MyObject :NSObject <MyObjectExport>
 
//this method is not accessible in javascript
-(void) test;
 
@end;
 
@implementation MyObject
@synthesize x;
 
-(int) getX
{
    return self.x;
}
+(MyObject *) getSqure:(MyObject*)obj;
{
    NSLog(@"Calling getSqure");
    MyObject * newObj = [MyObject new];
    newObj.x = obj.x * obj.x;
 
    return  newObj;
}

Now MyObject(Objective-C)’s variables and functions are directly accessed from javascript.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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]);
 
转:http://hayageek.com/execute-javascript-in-ios/

Execute Javascript in iOS Applications的更多相关文章

  1. React Native 简介:用 JavaScript 搭建 iOS 应用(2)

    [编者按]本篇文章的作者是 Joyce Echessa--渥合数位服务创办人,毕业于台湾大学,近年来专注于协助客户进行 App 软体以及网站开发.本篇文章中,作者介绍通过 React Native 框 ...

  2. React Native 简介:用 JavaScript 搭建 iOS 应用 (1)

    [编者按]本篇文章的作者是 Joyce Echessa--渥合数位服务创办人,毕业于台湾大学,近年来专注于协助客户进行 App 软体以及网站开发.本篇文章中,作者介绍通过 React Native 框 ...

  3. [Robot Framework] Robot Framework用Execute Javascript对XPath表示的元素执行scrollIntoView操作

    有些元素需要通过滚动条滚动才能变得可见. 如果这些元素在DOM结构里面存在,可以通过scrollIntoView让其可见,但如果在DOM结构里面不存在那就要通过拖动滚动条让其变的可见. Execute ...

  4. [Robot Framework] Robot Framework用Execute Javascript对XPath表示的元素执行Click操作

    Execute Javascript document.evaluate("//a[contains(@href,'createBook')]", document, null, ...

  5. javascript与 ios通讯解决办法

    阔别1年半之久,一个JavaScript和ios通讯的想法终于被实现了(我不知道别人有没有早就实现过~). 记得早期ios内嵌html做通讯时,貌似做好的办法只能是 ios通过url来截取页面发送消息 ...

  6. (转)Selenium-11: Execute JavaScript with JavascriptExecutor

    Outline Sometimes we cannot handle some conditions or problems with Webdriver, web controls don’t re ...

  7. javascript开发 ios和android app的简单介绍

    先看几个名词解释: nodejs ionic,Cordova,phoneGap,anjularjs react-native,reactjs nodeJs 的介绍参见这里,写的很好http://www ...

  8. Integrating JavaScript into Native Applications

    JavaScriptCore 简介 iOS7 中新加入的 JavaScriptCore.framework 可能被大多数开发人员所忽略,但是如果你之前就在项目中用过自己编译JavaScriptCore ...

  9. [转]Disabling ASLR on individual iOS applications when using iOS 6.0.1

    ASLR: Address Space Layout Randomization 查看应用是否进行了 ASLR 保护的方法:otool -hv ${File-Path} I recently enco ...

随机推荐

  1. 一个无锁消息队列引发的血案(三)——地:q3.h 与 RingBuffer

    目录 (一)起因 (二)混合自旋锁 (三)q3.h 与 RingBuffer (四)RingQueue(上) 自旋锁 (五)RingQueue(中) 休眠的艺术 (六)RingQueue(中) 休眠的 ...

  2. springboot中url地址重写(urlwrite)

    在日常网站访问中,会把动态地址改造成伪静态地址. 例如: 访问新闻栏目 /col/1/,这是原有地址,如果这样访问,不利于搜索引擎检索收录,同时安全性也不是很好. 改造之后: /col/1.html. ...

  3. 用Java检测远程主机是否能被连接

    有人推荐使用java的Runtime.exec()方法来直接调用系统的Ping命令.也有人完成了纯Java实现Ping的程序,使用的是Java的NIO包(native io, 高效IO包).我个人认为 ...

  4. [整理] mysql操作

    0.启动mysql(在windows中MySql以服务形式存在,在使用前应确保此服务已经启动) net start mysql 0.5获取版本信息 select version(); 1.root 登 ...

  5. Web前端开发规范文档你需要知道的事

    Web前端开发规范文档你需要知道的事 规范目的 为提高团队协作效率, 便于后台人员添加功能及前端后期优化维护, 输出高质量的文档, 特制订此文档. 本规范文档一经确认, 前端开发人员必须按本文档规范进 ...

  6. .NetCore使用Swagger进行单版本或多版本控制处理

    前面已经介绍过了Swagger的基础使用了 下面继续分别详细说明下 不添加版本控制以及添加版本控制的使用情况,其实也基本一致,对看起来可能更加容易理解 第一步 导入nuget包 nuget导入Swas ...

  7. IdentityServer4结合AspNetCore.Identity实现登录认证踩坑填坑记录

    也可以自定义实现,不使用IdentityServer4.AspNetIdentity这个包,当然还要实现其他接口IResourceOwnerPasswordValidator. IProfileSer ...

  8. 只想写一个真正能用的django mock

    调参数的过程,百转千回. 还好,搞得差不多了. 确实,方便写测试用例, 也是一个开发水平高低的衡量~~~:( 为了测试这个mock,不得不改下代码~~ 还要不断的将Model里允许Null的参数写完, ...

  9. 在 Vim 中优雅地查找和替换

    原文更好看链接http://harttle.com/2016/08/08/vim-search-in-file.html 总有人问我 Vim 中能不能查找,当然能!而且是超级强的查找! 这篇文章来详细 ...

  10. 使用ApiPost模拟发送get、post、delete、put等http请求

    现在的模拟发送请求插件很多比如老外的postman等,但亲测咱们国内的 ApiPost 更好用一些,因为它不仅可以模拟发送get.post.delete.put请求,还可以导出文档,支持团队协作也是它 ...