JavaScriptCore是apple推出的为了解决ios与js交互的框架,功能强大而实用。
一、JavaScriptCore中主要的类
1.1、JSContext — 在OC中创建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
| - (instancetype)init;
- (instancetype)initWithVirtualMachine:(JSVirtualMachine *)virtualMachine;
- (JSValue *)evaluateScript:(NSString *)script;
- (JSValue *)evaluateScript:(NSString *)script withSourceURL:(NSURL *)sourceURL NS_AVAILABLE(10_10, 8_0);
+ (JSContext *)currentContext;
+ (JSValue *)currentCallee NS_AVAILABLE(10_10, 8_0);
+ (JSValue *)currentThis;
+ (NSArray *)currentArguments;
@property (readonly, strong) JSValue *globalObject;
|
1.2、JSValue — JavaScript中的变量和方法,可以转成OC数据类型,每个JSValue都和JSContext相关联并且强引用context
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 52
| 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 // textFunction // - (void) ocTestFunction:(NSNumber *)value sec:(NSNumber *)number JSExportAs (textFunction,- (void) ocTestFunction:(NSNumber *)value sec:(NSNumber *)number); JSManagedValue
JSManagedValue *_jsManagedValue = [JSManagedValue managedValueWithValue:jsValue]; [_context.virtualMachine addManagedReference:_jsManagedValue]; JSManagedValue本身只弱引用js值,需要调用JSVirtualMachine的addManagedReference:withOwner:把它添加到JSVirtualMachine中,这样如果JavaScript能够找到该JSValue的Objective-C owner,该JSValue的引用就不会被释放。 JSVirtualMachine
|
下面记录一下使用方法:
二、简单的情况,JS中点击事件直接调用方法方式
2.1 JS代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| <!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>
|
2.2 oc代码如下:
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
| - (void)doSomeJsThings{ self.jsContext = [_webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"]; self.jsContext.exceptionHandler = ^(JSContext *context, JSValue *exception) { NSLog(@"出现异常,异常信息:%@",exception); }; JSValue * nativeCallJS = self.jsContext[@"nativeCallJS"]; [nativeCallJS callWithArguments:@[@"hello word"]]; self.jsContext[@"jsCallNative"] = ^(NSString *paramer){ JSValue *currentThis = [JSContext currentThis]; JSValue *currentCallee = [JSContext currentCallee]; NSArray *currentParamers = [JSContext currentArguments]; dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"js传过来:%@",paramer); }); NSLog(@"JS paramer is %@",paramer); NSLog(@"currentThis is %@",[currentThis toString]); NSLog(@"currentCallee is %@",[currentCallee toString]); NSLog(@"currentParamers is %@",currentParamers); }; }
|
1 2 3 4 5 6 7 8 9
| 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代码的互调如下:
3.1 JS代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| <!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>
|
3.2 oc代码如下:
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 52 53 54 55 56 57 58 59 60 61 62 63 64
| @protocol JSObjcDelegate <JSExport>
- (void)jsCallNative; - (void)shareString:(NSString *)shareString;
@end
- (void)doSomeJsThings{ self.jsContext = [_webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"]; self.jsContext.exceptionHandler = ^(JSContext *context, JSValue *exception) { NSLog(@"出现异常,异常信息:%@",exception); }; JSValue * jsObj = self.jsContext[@"globalObject"]; JSValue * returnValue = [jsObj invokeMethod:@"nativeCallJS" withArguments:@[@"hello word"]]; NSLog(@"returnValue:%@",returnValue); JSValue * jsCallNative = [JSValue valueWithObject:self inContext:self.jsContext]; self.jsContext[@"NativeObject"] = jsCallNative; }
- (void)jsCallNative{ JSValue *currentThis = [JSContext currentThis]; JSValue *currentCallee = [JSContext currentCallee]; NSArray *currentParamers = [JSContext currentArguments]; dispatch_async(dispatch_get_main_queue(), ^{
}); NSLog(@"currentThis is %@",[currentThis toString]); NSLog(@"currentCallee is %@",[currentCallee toString]); NSLog(@"currentParamers is %@",currentParamers); }
- (void)shareString:(NSString *)shareString{ JSValue *currentThis = [JSContext currentThis]; JSValue *currentCallee = [JSContext currentCallee]; NSArray *currentParamers = [JSContext currentArguments]; dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"js传过来:%@",shareString); }); NSLog(@"JS paramer is %@",shareString); NSLog(@"currentThis is %@",[currentThis toString]); NSLog(@"currentCallee is %@",[currentCallee toString]); NSLog(@"currentParamers is %@",currentParamers); }
|
打印的log:
1 2 3 4 5 6
| 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 ( )
|
1 2 3 4 5 6 7 8 9
| 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 )
|
四,特殊要求
4.1 、JS中对象已经生成,需要OC生成对应的方法实现,JS去调用
JS代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| <!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代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| - (void)doSomeJsThings{ self.jsContext = [_webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"]; self.jsContext.exceptionHandler = ^(JSContext *context, JSValue *exception) { NSLog(@"出现异常,异常信息:%@",exception); }; JSValue * jsObj = self.jsContext[@"globalObject"]; jsObj[@"creatJSMethod"] = ^(NSString * parameter){ NSLog(@"方法生成成功:%@",parameter); }; }
|
log:
2017-11-15 14:47:08.126160+0800 WebView+image[3661:435044] 方法生成成功:jsParameter
4.2、oc重写js本地的方法,与生成一样,上面的代码:
1 2 3
| jsObj[@"creatJSMethod"] = ^(NSString * parameter){ NSLog(@"方法生成成功:%@",parameter); };
|
既能生成,也能重写。
这些基本就是全部的情况了,当然还有一些线程问题等,等有需要再总结。
总结:
oc与js交互,先看js是调oc还是oc调用js,再看js中方法是全局方法还是全局属性方法(可能说的不是很准确)。清楚了这些就好实现了!!!
iOS WKWebView与JS交互