WKWebView、WebView和JS的交互方式详解

2020-01-21 05:36:14于丽

 JS部分:


//JS响应事件
function btnClick() { window.webkit.messageHandlers.playSound.postMessage(null);
}

利用JavaScriptCore库,WebView与JS的交互

一,OC调用JS


self.jsContent = [[JSContext alloc] init];
 
NSString *js = @"function add(a,b) {return a + b}";
[self.jsContent evaluateScript:js];
JSValue *jsValue = [self.jsContent[@"add"] callWithArguments:@[@2,@3]];

二,JS调用OC


self.jsContent = [[JSContext alloc] init];
self.jsContent[@"add"] = ^(int a, int b){
 NSLog(@"a+b = %d",a+b);
};
 
[self.jsContent evaluateScript:@"add(10,20)"];

三,JS直接访问OC对象方法与属性

1.首先定义一个协议,这个协议遵守JSExport协议


@protocol JSExportTest <JSExport>
@property (nonatomic, assign) NSInteger sum;
JSExportAs(add, - (NSInteger)add:(int)a b:(int)b);
 
@end

其中JSExportAs()是系统提供的宏,用来声明在JS环境中方法add与OC环境中方法- (NSInteger)add:(int)a b:(int)b对应。

2.创建一类,遵守JSExportTest协议,并实现它什么的方法与属性


@interface JSProtolObj : NSObject <JSExportTest>
@end
@implementation JSProtolObj
@synthesize sum = _sum;
- (NSInteger)add:(int)a b:(int)b {
 return a+b;
}
 
- (void)setSum:(NSInteger)sum {
 _sum = sum;
}
@end

3.使用方式:


self.jsContent = [[JSContext alloc] init];
self.jsContent.exceptionHandler = ^(JSContext *context, JSValue *exception) {
 [JSContext currentContext].exception = exception;
 NSLog(@"exception:%@",exception);
};
 
self.jsContent[@"OCobj"] = self.jsProtolObj;
[self.jsContent evaluateScript:@"OCobj.sum = OCobj.add(10,20)"];

这三种使用方式可以根据实际情况进行适当使用

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对ASPKU的支持。


注:相关教程知识阅读请移步到IOS开发频道。