因為項目需求驅動需求。折騰了幾天,由于之前沒有UIWebView與JS交互的經歷,并且覺得這次寫完之后感覺以后原生的app和js交互會越來越多,特此留下一點文字,方便日后回顧。
在這我用兩種方式小談UIWebView與JS交互,和一種WKWebView和js交互,相關的項目已上傳github,有些興趣的可以在后文中下載查看。
首先說一下UIWebView與JS的交互
初始化UIWebView
UIWebView *web = [[UIWebView alloc]initWithFrame:[UIScreen mainScreen].bounds];
1.這是加載網絡連接的形式
// NSURL *url = [NSURL URLWithString:@"https://baidu.com"];
// NSURLRequest *request = [NSURLRequest //requestWithURL:url];
// [web loadRequest:request];
2.加載本地html
//首先創建webView加載本地的html文件
NSString *path = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"JSCallOC.html"];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]];
[self.webView loadRequest:request];
[self.view addSubview:web];
相關的代理方法
- (void)webViewDidStartLoad:(UIWebView *)webView{
}
- (void)webViewDidFinishLoad:(UIWebView *)webView{
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
}
方式一
第一種方式是用JS發起一個響應的URL請求,然后利用UIWebView的代理方法攔截這次請求,然后再做相應的處理。
我寫了一個簡單的HTML網頁和一個btn點擊事件用來與原生OC交互,HTML代碼如下:
<html>
<!--描述網頁信息-->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>小黃</title>
<style>
.btn{height:40px; width:60%; padding: 0px 30px; background-color: #0071E7; border: solid 1px #0071E7; border-radius:5px; font-size: 1.2em; color: white}
</style>
<script>
function clear(){
document.getElementById('mobile').innerHTML = ''
document.getElementById('name').innerHTML = ''
document.getElementById('msg').innerHTML = ''
}
//提供給OC調用JS的方法列表
function alertMobile() {
//alert('我是上面的小黃 手機號是:13300001111')
document.getElementById('mobile').innerHTML = '我是上面的小黃 手機號是:13300001111'
}
function alertName(msg) {
//alert('你好 ' + msg + ', 我也很高興見到你')
document.getElementById('name').innerHTML = '你好 ' + msg + ', 我也很高興見到你'
}
function alertSendMsg(num,msg) {
//alert('這是我的手機號:' + num + ',' + msg + '!!')
document.getElementById('msg').innerHTML = '這是我的手機號:' + num + ',' + msg + '!!'
}
//JS調用oc響應方法列表
function btnClick1() {
location.href = "rrcc://showMobile"
}
function btnClick2() {
location.href = "rrcc://showName_?xiaohuang"
}
function btnClick3() {
location.href = "rrcc://showSendNumber_msg_?13300001111&go climbing this weekend"
}
</script>
</head>
<!--網頁具體內容-->
<body>
<br/><br/>
<div>
<label>小黃:13300001111</label>
</div>
<br/><br/>
<div id="mobile"></div>
<br/>
<div>
<button class="btn" type="button" onclick="btnClick1()">小紅的手機號</button>
</div>
<br/>
<div id="name"></div>
<br/>
<div>
<button class="btn" type="button" onclick="btnClick2()">打電話給小紅</button>
</div>
<br/>
<div id="msg"></div>
<br/>
<div>
<button class="btn" type="button" onclick="btnClick3()">發短信給小紅</button>
</div>
</body>
</html>
然后在項目的控制器中實現UIWebView的代理方法:
#pragma mark - UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
NSLog(@"%@",NSStringFromSelector(_cmd));
//OC調用JS是基于協議攔截實現的 下面是相關操作
NSString *absolutePath = request.URL.absoluteString;
NSString *scheme = @"rrcc://";
if ([absolutePath hasPrefix:scheme]) {
NSString *subPath = [absolutePath substringFromIndex:scheme.length];
if ([subPath containsString:@"?"]) {//1個或多個參數
if ([subPath containsString:@"&"]) {//多個參數
NSArray *components = [subPath componentsSeparatedByString:@"?"];
NSString *methodName = [components firstObject];
methodName = [methodName stringByReplacingOccurrencesOfString:@"_" withString:@":"];
SEL sel = NSSelectorFromString(methodName);
NSString *parameter = [components lastObject];
NSArray *params = [parameter componentsSeparatedByString:@"&"];
if (params.count == 2) {
if ([self respondsToSelector:sel]) {
[self performSelector:sel withObject:[params firstObject] withObject:[params lastObject]];
}
}
} else {//1個參數
NSArray *components = [subPath componentsSeparatedByString:@"?"];
NSString *methodName = [components firstObject];
methodName = [methodName stringByReplacingOccurrencesOfString:@"_" withString:@":"];
SEL sel = NSSelectorFromString(methodName);
NSString *parameter = [components lastObject];
if ([self respondsToSelector:sel]) {
[self performSelector:sel withObject:parameter];
}
}
} else {//沒有參數
NSString *methodName = [subPath stringByReplacingOccurrencesOfString:@"_" withString:@":"];
SEL sel = NSSelectorFromString(methodName);
if ([self respondsToSelector:sel]) {
[self performSelector:sel];
}
}
}
return YES;
}
注意:1. 通過scheme進行攔截到我們需要的url做出響應的判斷。
2.html中需要設置編碼,否則中文參數可能會出現編碼問題。
3.JS用直接用document.location的方式,這是一種早期的交互方式,現在oc里面有一個javascriptcore的框架,后面在詳解。
早期的JS與原生交互的開源庫很多都是用得這種方式來實現的,例如:PhoneGap、WebViewJavascriptBridge。關于這種方式調用OC方法,唐巧早期有篇文章有過介紹:關于UIWebView和PhoneGap的總結
方式二
在iOS 7之后,apple添加了一個新的庫JavaScriptCore,用來做JS交互,因此JS與原生OC交互也變得簡單了許多。
首先導入JavaScriptCore庫, 然后在OC中獲取JS的上下文
- JS調OC方法
首先導入頭文件
#import <JavaScriptCore/JavaScriptCore.h>
屬性中添加
@property (strong, nonatomic) JSContext *context;
JS調用OC方法一般在WebView的代理方法中實現
#pragma mark - UIWebViewDelegate
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
// 以 html title 設置 導航欄 title
self.title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
// 禁用 頁面元素選擇
//[webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitUserSelect='none';"];
// 禁用 長按彈出ActionSheet
//[webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitTouchCallout='none';"];
// Undocumented access to UIWebView's JSContext
self.context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
// 打印異常
self.context.exceptionHandler =
^(JSContext *context, JSValue *exceptionValue)
{
context.exception = exceptionValue;
NSLog(@"%@", exceptionValue);
};
// 以 JSExport 協議關聯 native 的方法
self.context[@"native"] = self;
// 以 block 形式關聯 JavaScript function
self.context[@"log"] =
^(NSString *str)
{
NSLog(@"%@", str);
};
// 以 block 形式關聯 JavaScript function
self.context[@"alert"] =
^(NSString *str)
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"msg from js" message:str delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];
[alert show];
};
__block typeof(self) weakSelf = self;
self.context[@"addSubView"] =
^(NSString *viewname)
{
UIView *view = [[UIView alloc]initWithFrame:CGRectMake(10, 500, 300, 100)];
view.backgroundColor = [UIColor redColor];
UISwitch *sw = [[UISwitch alloc]init];
[view addSubview:sw];
[weakSelf.view addSubview:view];
};
//多參數
self.context[@"mutiParams"] =
^(NSString *a,NSString *b,NSString *c)
{
NSLog(@"%@ %@ %@",a,b,c);
};
}
以上只是相關主要代碼,詳細的請移步github查看
OC調JS
- 初始化JSContext
- 加載js文件
- 在oc中創建JSValue代表JS中的對象,讓JS對象去執行方法
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
self.title = @"oc call js";
self.context = [[JSContext alloc] init];
[self.context evaluateScript:[self loadJsFile:@"test"]];
}
- (NSString *)loadJsFile:(NSString*)fileName
{
NSString *path = [[NSBundle mainBundle] pathForResource:fileName ofType:@"js"];
NSString *jsScript = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
return jsScript;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)sendToJS:(id)sender {
NSNumber *inputNumber = [NSNumber numberWithInteger:[self.textField.text integerValue]];
JSValue *function = [self.context objectForKeyedSubscript:@"factorial"];
JSValue *result = [function callWithArguments:@[inputNumber]];
self.showLable.text = [NSString stringWithFormat:@"%@", [result toNumber]];
}
以上是關于UIWebView和js的交互。
戳這里:本文的DEMO地址歡迎star,下載。
戳這里:本文的DEMO地址-JavaScriptCore歡迎star,下載。