iOS JavaScriptCore使用

JavaScriptCore是apple推出的为了解决ios与js交互的框架,功能强大而实用。

##JavaScriptCore中主要的类

1、JSContext --- 在OC中创建JavaScript运行的上下文环境

 - (instancetype)init; // 创建JSContext对象,获得JavaScript运行的上下文环境

 // 在特定的对象空间上创建JSContext对象,获得JavaScript运行的上下文环境
 - (instancetype)initWithVirtualMachine:(JSVirtualMachine *)virtualMachine;

 // 运行一段js代码,输出结果为JSValue类型
 - (JSValue *)evaluateScript:(NSString *)script;

 // iOS 8.0以后可以调用此方法
 - (JSValue *)evaluateScript:(NSString *)script withSourceURL:(NSURL *)sourceURL NS_AVAILABLE(10_10, 8_0);

 // 获取当前正在运行的JavaScript上下文环境
 + (JSContext *)currentContext;

 // 返回结果当前执行的js函数 function () { [native code] } ,iOS 8.0以后可以调用此方法
  + (JSValue *)currentCallee NS_AVAILABLE(10_10, 8_0);

  // 返回结果当前方法的调用者[object Window]
  + (JSValue *)currentThis;

  // 返回结果为当前被调用方法的参数
  + (NSArray *)currentArguments;

  // js的全局变量 [object Window]
  @property (readonly, strong) JSValue *globalObject;
复制代码

2、JSValue --- JavaScript中的变量和方法,可以转成OC数据类型,每个JSValue都和JSContext相关联并且强引用context

   oc与js类型对照:
      @textblock
     Objective-C type  |   JavaScript type
   --------------------+---------------------
           nil         |     undefined
          NSNull       |        null
         NSString      |       string
         NSNumber      |   number, boolean
       NSDictionary    |   Object object
         NSArray       |    Array object
          NSDate       |     Date object
         NSBlock (1)   |   Function object (1)
            id (2)     |   Wrapper object (2)
          Class (3)    | Constructor object (3)
      @/textblock

  //此方法会转换self为JS对象,但是self中必须实现指定的方法和协议
  + (JSValue *)valueWithObject:(id)value inContext:(JSContext *)context;

  // 在context创建BOOL的JS变量
  + (JSValue *)valueWithBool:(BOOL)value inContext:(JSContext *)context;

  // 将JS变量转换成OC中的BOOL类型
  - (BOOL)toBool;

  // 修改JS对象的属性的值
  - (void)setValue:(id)value forProperty:(NSString *)property;

  // JS中是否有这个对象
  @property (readonly) BOOL isUndefined;

  // 比较两个JS对象是否相等
  - (BOOL)isEqualToObject:(id)value;

  // 调用者JSValue为JS中的方法,arguments为参数,执行调用者JSValue,并传递参数arguments,@[@"a",@"b"@"c"]
  - (JSValue *)callWithArguments:(NSArray *)arguments;

 // 调用者JSValue为JS中的全局对象名称,method为全局对象的方法名称,arguments为参数
  - (JSValue *)invokeMethod:(NSString *)method withArguments:(NSArray *)arguments;

 // JS中的结构体类型转换为OC
  + (JSValue *)valueWithPoint:(CGPoint)point inContext:(JSContext *)context;
JSExport --- JS调用OC中的方法和属性写在继承自JSExport的协议当中,OC对象实现自定义的协议
 // textFunction -- JS方法
 // - (void) ocTestFunction:(NSNumber *)value sec:(NSNumber *)number -- OC方法
 JSExportAs (textFunction,- (void) ocTestFunction:(NSNumber *)value sec:(NSNumber *)number);
JSManagedValue --- JS和OC对象的内存管理辅助对象,主要用来保存JSValue对象,解决OC对象中存储js的值,导致的循环引用问题

 JSManagedValue *_jsManagedValue = [JSManagedValue managedValueWithValue:jsValue];
[_context.virtualMachine addManagedReference:_jsManagedValue];
JSManagedValue本身只弱引用js值,需要调用JSVirtualMachine的addManagedReference:withOwner:把它添加到JSVirtualMachine中,这样如果JavaScript能够找到该JSValue的Objective-C owner,该JSValue的引用就不会被释放。
JSVirtualMachine --- JS运行的虚拟机,有独立的堆空间和垃圾回收机制,运行在不同虚拟机环境的JSContext可以通过此类通信。
复制代码

下面记录一下使用方法:

##一、简单的情况,JS中,点击事件直接调用方法方式 1.1 JS代码如下:

<!DOCTYPE html>
<html>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta content="width=device-width,initial-scale=1,user-scalable=no" name="viewport">

<body style="background-color: white;">
    <script type="text/javascript">
        var nativeCallJS = function(parameter) {
            alert (parameter);
        };
    </script>
    <button type="button" onclick = "jsCallNative('jsParameter')" style="width:100%; height:30px;"/>调用OC代码</button>
</body>
</html>
复制代码

1.2 oc代码如下:

- (void)doSomeJsThings{
    
    self.jsContext = [_webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    self.jsContext.exceptionHandler = ^(JSContext *context, JSValue *exception) {
        NSLog(@"出现异常,异常信息:%@",exception);
    };
    
    //oc调用js
    JSValue * nativeCallJS = self.jsContext[@"nativeCallJS"];
    [nativeCallJS callWithArguments:@[@"hello word"]];//调用了js中方法"nativeCallJS",并且传参数@"hello word"
    
    //在本地生成js方法,供js调用
    self.jsContext[@"jsCallNative"] = ^(NSString *paramer){
        JSValue *currentThis = [JSContext currentThis];
        JSValue *currentCallee = [JSContext currentCallee];
        NSArray *currentParamers = [JSContext currentArguments];
        dispatch_async(dispatch_get_main_queue(), ^{
            /**
             *  js调起OC代码,代码在子线程,更新OC中的UI,需要回到主线程
             */
            NSLog(@"js传过来:%@",paramer);
        });
        NSLog(@"JS paramer is %@",paramer);
        NSLog(@"currentThis is %@",[currentThis toString]);
        NSLog(@"currentCallee is %@",[currentCallee toString]);
        NSLog(@"currentParamers is %@",currentParamers);
    };//生成native的js方法,方法名:@"jsCallNative",js可直接调用此方法
}
复制代码
2017-11-15 13:30:37.715810+0800 WebView+image[2940:337555] js传过来:jsParameter
2017-11-15 13:30:37.715759+0800 WebView+image[2940:337892] JS paramer is jsParameter
2017-11-15 13:30:37.716007+0800 WebView+image[2940:337892] currentThis is [object Window]
2017-11-15 13:30:37.716337+0800 WebView+image[2940:337892] currentCallee is function () {
    [native code]
}
2017-11-15 13:30:37.716743+0800 WebView+image[2940:337892] currentParamers is (
    jsParameter
)
复制代码

以上就是简单的调用。

##二、复杂调用,JS中,点击事件等事件通过调用全局对象的方法调用方法,JS和Native代码的互调如下: 2.1 JS代码如下:

<!DOCTYPE html>
<html>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta content="width=device-width,initial-scale=1,user-scalable=no" name="viewport">
<body style="background-color: white;">

    <script type="text/javascript">
        globalObject = new Object();
        globalObject.name = 100;
        globalObject.nativeCallJS = function (parameter) {
            alert (parameter);
        };
    </script>
    
    <button type="button" onclick = "NativeObject.jsCallNative()" style="width:100%; height:30px;"/>调用OC代码</button>
    <button type="button" onclick = "NativeObject.shareString('jsParameter')" style="width:100%; height:30px;"/>调用OC代码并传参数</button>
</body>
</html>
复制代码

2.2 oc代码如下:

//声明的协议,当前viewController必须遵守
@protocol JSObjcDelegate <JSExport>

- (void)jsCallNative;
- (void)shareString:(NSString *)shareString;

@end

//方法实现,在webViewDidFinishLoad中调用
- (void)doSomeJsThings{
    
    self.jsContext = [_webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    self.jsContext.exceptionHandler = ^(JSContext *context, JSValue *exception) {
        NSLog(@"出现异常,异常信息:%@",exception);
    };
    
    //oc调用js
    JSValue * jsObj = self.jsContext[@"globalObject"];//拿到js中要调用方法的全局对象
    //jsObj执行其方法nativeCallJS
    JSValue * returnValue = [jsObj invokeMethod:@"nativeCallJS" withArguments:@[@"hello word"]];
   //调用了js中方法"nativeCallJS",并且传参数@"hello word",这里returnValue是调用之后的返回值,可能为nil
    NSLog(@"returnValue:%@",returnValue);
    
    //写法1
    JSValue * jsCallNative = [JSValue valueWithObject:self inContext:self.jsContext];//此方法会转换self为JS对象,但是self中必须实现指定的方法和协议
    self.jsContext[@"NativeObject"] = jsCallNative;
    //写法2
    //self.jsContext[@"NativeObject"] = self;
    //注:写法1和写法2效果相同,推荐写法1,毕竟系统方法
}

- (void)jsCallNative{//在本地生成js方法,供js调用
    
    JSValue *currentThis = [JSContext currentThis];
    JSValue *currentCallee = [JSContext currentCallee];
    NSArray *currentParamers = [JSContext currentArguments];
    dispatch_async(dispatch_get_main_queue(), ^{
        /**
         *  js调起OC代码,代码在子线程,更新OC中的UI,需要回到主线程
         */
    });
    NSLog(@"currentThis is %@",[currentThis toString]);
    NSLog(@"currentCallee is %@",[currentCallee toString]);
    NSLog(@"currentParamers is %@",currentParamers);
    
}


- (void)shareString:(NSString *)shareString{//在本地生成js方法,供js调用
    
    JSValue *currentThis = [JSContext currentThis];
    JSValue *currentCallee = [JSContext currentCallee];
    NSArray *currentParamers = [JSContext currentArguments];
    dispatch_async(dispatch_get_main_queue(), ^{
        /**
         *  js调起OC代码,代码在子线程,更新OC中的UI,需要回到主线程
         */
        NSLog(@"js传过来:%@",shareString);
    });
    NSLog(@"JS paramer is %@",shareString);
    NSLog(@"currentThis is %@",[currentThis toString]);
    NSLog(@"currentCallee is %@",[currentCallee toString]);
    NSLog(@"currentParamers is %@",currentParamers);
}
复制代码

打印的log:

2017-11-15 14:02:18.695352+0800 WebView+image[3257:377010] currentThis is [object SecondViewController]
2017-11-15 14:02:18.695745+0800 WebView+image[3257:377010] currentCallee is function () {
    [native code]
}
2017-11-15 14:02:18.695936+0800 WebView+image[3257:377010] currentParamers is (
)
复制代码
2017-11-15 14:02:50.904847+0800 WebView+image[3257:376893] js传过来:jsParameter
2017-11-15 14:02:50.904842+0800 WebView+image[3257:377010] JS paramer is jsParameter
2017-11-15 14:02:50.905124+0800 WebView+image[3257:377010] currentThis is [object SecondViewController]
2017-11-15 14:02:50.905607+0800 WebView+image[3257:377010] currentCallee is function () {
    [native code]
}
2017-11-15 14:02:50.906052+0800 WebView+image[3257:377010] currentParamers is (
    jsParameter
)
复制代码

##三,特殊要求 3.1 、JS中对象已经生成,需要OC生成对应的方法实现,JS去调用 JS代码如下:

<!DOCTYPE html>
<html>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta content="width=device-width,initial-scale=1,user-scalable=no" name="viewport">
<body style="background-color: white;">
    <script type="text/javascript">
        globalObject = new Object();
        globalObject.name = 100;
        globalObject.nativeCallJS = function (parameter) {
            alert (parameter);
        };
    
        var callBack = function(parameter){
            alert(parameter);
        }
    </script>
    
    <button type="button" onclick = "NativeObject.jsCallNative()" style="width:100%; height:30px;"/>调用OC代码</button>
    <button type="button" onclick = "NativeObject.shareString('jsParameter')" style="width:100%; height:30px;"/>调用OC代码并传参数</button>
    <button type="button" onclick = "globalObject.creatJSMethod('jsParameter')" style="width:100%;height:30px;"/>oc生成JS方法</button>
</body>
</html>
复制代码

以上JS中globalObject对象已经存在,但是在没有实现creatJSMethod方法,在按钮"oc生成JS方法"却调用了此方法。 OC代码:

- (void)doSomeJsThings{
    
    self.jsContext = [_webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    self.jsContext.exceptionHandler = ^(JSContext *context, JSValue *exception) {
        NSLog(@"出现异常,异常信息:%@",exception);
    };
    
    //oc调用js
    JSValue * jsObj = self.jsContext[@"globalObject"];//拿到JS中已经存在的对象
    //为jsObj对应的方法提供方法实现
    jsObj[@"creatJSMethod"] = ^(NSString * parameter){
        NSLog(@"方法生成成功:%@",parameter);
    };
  }
复制代码

log:

2017-11-15 14:47:08.126160+0800 WebView+image[3661:435044] 方法生成成功:jsParameter
复制代码

3.2、oc重写js本地的方法,与生成一样,上面的代码:

 jsObj[@"creatJSMethod"] = ^(NSString * parameter){
    NSLog(@"方法生成成功:%@",parameter);
 };
复制代码

既能生成,也能重写。

这些基本就是全部的情况了,当然还有一些线程问题等,等有需要再总结。

#####总结: oc与js交互,先看js是调oc还是oc调用js,再看js中方法是全局方法还是全局属性方法(可能说的不是很准确)。清楚了这些就好实现了!!!

iOS WKWebView与JS交互

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值