JS呼叫Native方法(OC)
最近用到js呼叫原生方法,在這裡做個總結記錄。
呼叫原生時會用到JSContext,官方文件解釋如下:
/*!
@interface
@discussion A JSContext is a JavaScript execution environment. All
JavaScript execution takes place within a context, and all JavaScript values
are tied to a context.
*/
JSContext是一個JS執行環境,也就是上下文的意思吧,也就相當於拿到了這個JSContext拿到了JS執行環境,可以利用JSContext直接進行操作JS。
使用:
1.宣告一個協議MyJSExport,這個協議必須遵循 JSExport,給協議新增協議方法,協議方法必須是required
2.建立一個物件這個物件必須遵循MyJSExport協議,或者為一個物件新增MyJSExport協議
3.例項化一個JSContext物件,jsContext
4.給新建立的JSContext物件賦值,並呼叫對應的方法
- (void)webViewDidFinishLoad:(UIWebView *)webView {
self.jsContext = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
//這種方法不需要構建物件模型,也就是上面的1、2步都不需要 但是新增一個方法都需要寫一個block
self.jsContext[@"test1"] = ^(){
};
//方法二 模型注入 在JS中直接呼叫NAtiveObject.方法名 就可以了(方法必須在MyJSExport協議中宣告)
self.jsContext[@"NativeObject"] = self;
}
程式碼部分:
WebViewViewController.m
#import "WebViewViewController.h"
#import <JavaScriptCore/JavaScriptCore.h>
@protocol MyJSExport <JSExport>
- (void)test1;
- (void)test2;
@end
@interface WebViewViewController ()<UIWebViewDelegate,MyJSExport>
@property (nonatomic,strong) JSContext *jsContext;
@property (nonatomic,strong) UIWebView *webView;
@end
@implementation WebViewViewController
- (void)viewDidLoad {
self.webView = [[UIWebView alloc] init];
self.webView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
self.webView.delegate = self;
[self.view addSubview:self.webView];
NSURL *url = [[NSBundle mainBundle] URLForResource:@"a" withExtension:@"html"];
[self.webView loadRequest:[NSURLRequest requestWithURL:url]];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView {
self.jsContext = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
self.jsContext.exceptionHandler = ^(JSContext *context, JSValue *ex){
context.exception = ex;
NSLog(@"異常資訊%@",ex);
};
self.jsContext[@"NativeObject"] = self;
self.jsContext[@"test1"] = ^(){
NSLog(@"test1呼叫了");
};
}
- (void)test2{
NSLog(@"方法2呼叫了");
}
a.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>JSAndNative</title>
</head>
<style>
.main-wrap ul {
width: 100%;
display: inline-block;
padding-top: 20px;
}
.main-wrap ul li {
float: left;
width: 100%;
height: 40px;
line-height: 40px;
font-size: 14px;
margin-bottom: 20px;
background-color: #00D000;
color: #fff;
text-align: center;
}
.main-wrap ul li:active {
opacity: 0.8;
}
</style>
<body bgcolor="#dddd">
<div class="main-wrap">
<ul class="postNative">
<li onclick="JS_Native1()">fun1</li>
<li onclick="JS_Native2()">fun2</li>
</ul>
</div>
<script>
function JS_Native1() {
test1();
}
function JS_Native2() {
NativeObject.test2();
}
</script>
</body>
</html>