OC中提供了JavaScriptCore 这个库,使得OC与js的交互变得更加方便。
使用方法:
1 加入JavaScriptCore 这个framework
2 引入头文件<JavaScriptCore/JavaScriptCore.h>
3 在VC里面加入一个JSContext属性
@property (strong, nonatomic) JSContext *context;
JSContext是一个JS的执行环境,所有的JS执行都发生在一个context里面, 所有的JS value都绑定到context里面
test.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<link rel="stylesheet" href="">
<style type="text/css">
body {
background-color: green;
}
button {
position: absolute;
width: 300px;
height: 300px;
background-color: red;
}
</style>
</head>
<body>
<div id="id"></div>
<button onclick="jump('3')">点我</button>
<script type="text/javascript">
function jump(a) {
var div = document.getElementById('id');
div.innerHTML = a;
}
</script>
</body>
</html>
OC 文件
import <JavaScriptCore/JavaScriptCore.h>
@interface JSCViewController ()<UIWebViewDelegate>
@property (weak, nonatomic) IBOutlet UIWebView *webView;
@property (nonatomic,strong)JSContext *content;
//JSContext是一个JS的执行环境,所有的JS执行都发生在一个context里面, 所有的JS value都绑定到context里面
@end
@implementation JSCViewController
-
(void)viewDidLoad {
[super viewDidLoad];self.webView.delegate = self;
NSString filePath = [[NSBundle mainBundle] pathForResource:@"test.html" ofType:nil];
NSURL url = [NSURL fileURLWithPath:filePath];//创建URL
NSURLRequest* request = [NSURLRequest requestWithURL:url];//创建NSURLRequest
[self.webView loadRequest:request];//加载
//初始化context
self.content = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
}
pragma mark - btnAction
//-------------------通过OC调用此方法
-
(IBAction)OCJS:(UIButton *)sender {
//(1)例如html的script中一个方法
//function jump(a){
//}
NSString *method = @"jump";JSValue *function = [self.content objectForKeyedSubscript:method];
//方法调用
[function callWithArguments:@[@1]];
}
pragma mark - UIWebViewDelegate
// ----------------- JS调用OC
-
(void)webViewDidFinishLoad:(UIWebView *)webView{
//例如网页中有个标签,点击button的时候调用Jump方法, 此处3为传入的参数
// <button onclick="jump('3')">点我</button>//当点击网页中的button的时候,触发jump方法, 在OC中用如下代码可以捕捉到jump方法, 并拿到JS给我传的参数‘3’
self.content[@"jump"] = ^(NSString *str){
//此处 str 值为'3'(js调用OC时传给OC的参数)
NSLog(@"%@",str);
};
}