0.html+jsjavascript
0.1html 代码html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> #colordv{ width: 100px; height: 100px; margin: auto; background-color:red; } .icon{ } </style> </head> <body> <div id="colordv" class="icon"></div> <script src="1.js"></script> </body> </html>
0.2js代码java
//uiwebview function asyncAlert(text) { setTimeout(function(){ alert('这是来自网页的弹窗:' + text); },0); var obj = document.getElementById('colordv'); obj.sendText('这是来自网页的消息',obj); } //wkwebview window.onload = function(){ var obj = document.getElementById('colordv'); obj.onclick = function(){ shareList(['123','333','kkk']); this.style.backgroundColor = "pink"; } } function shareList(texts){ window.webkit.messageHandlers.shareList.postMessage(texts); } function wkAsyncAlert(text) { setTimeout(function(){ alert('这是来自网页的弹窗:' + text); },0); return '返回结果'; }
1.uiwebviewweb
1.0初始化代码app
UIWebView *webView = [[UIWebView alloc] initWithFrame:self.view.bounds]; [self.view addSubview:webView]; webView.delegate = self; NSString *path = [[NSBundle mainBundle] pathForResource:@"1.html" ofType:nil]; NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]]; [webView loadRequest:request];
1.1在代理方法中-(void)webViewDidFinishLoad:(UIWebView *)webView;async
JSContext *context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"]; JSValue *obj = context[@"colordv"]; //设置网页元素的方法,接收网页元素发送的消息 obj[@"sendText"] = ^(){ NSArray *args = [JSContext currentArguments]; NSLog(@"%@",args.firstObject); JSValue *btn = args.lastObject; btn[@"style"][@"backgroundColor"]=@"pink"; }; // __weak typeof(webView) weakView = webView; //设置网页元素的方法,并向网页发送消息 obj[@"onclick"] = ^(){ NSString *text = @"hello world"; NSString *jsStr = [NSString stringWithFormat:@"asyncAlert('%@')",text]; //oc 调用js的方法1: [[JSContext currentContext] evaluateScript:jsStr]; //oc 调用js的方法2: // [[JSContext currentContext][@"asyncAlert"] callWithArguments:@[@"hahaha"]]; //oc 调用js的方法3:必需主线程调用 // dispatch_async(dispatch_get_main_queue(), ^{ // __strong typeof(weakView) wv = weakView; // [wv stringByEvaluatingJavaScriptFromString:jsStr]; // }); };
总结:ide
1.js调用oc的方法大体就是,js中声明方法,使用方法,oc中实现方法post
2.oc调用js的方法大体就是调用方法:[webview evaluateScript:@"xxxx"];ui
2.wkwebviewthis
2.0初始化代码
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init]; WKPreferences *prefences = [[WKPreferences alloc] init]; prefences.javaScriptCanOpenWindowsAutomatically = YES; prefences.minimumFontSize = 30; config.preferences = prefences; WKWebView *webview = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:config]; [self.view addSubview:webview]; webview.UIDelegate = self; _wkWebView = webview; NSString *path = [[NSBundle mainBundle] pathForResource:@"1.html" ofType:nil]; NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]]; [_wkWebView loadRequest:request]; UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom]; [self.view addSubview:btn]; btn.backgroundColor = [UIColor redColor]; btn.frame = CGRectMake(100, 100, 80, 40); [btn setTitle:@"dada" forState:UIControlStateNormal]; [btn addTarget:self action:@selector(dadaClick:) forControlEvents:UIControlEventTouchUpInside];
说明:在wk中,js和oc的消息传递,大都是经过config来完成,须要经过config来添加或者删除消息
-(void)viewWillAppear:(BOOL)animated{ [super viewWillAppear:animated]; [_wkWebView.configuration.userContentController addScriptMessageHandler:self name:@"shareList"]; } -(void)viewWillDisappear:(BOOL)animated{ [super viewWillDisappear:animated]; [_wkWebView.configuration.userContentController removeScriptMessageHandlerForName:@"shareList"]; }
2.1js向oc发消息
此时须要修改js的代码,格式为:
function shareList(texts){ window.webkit.messageHandlers.shareList.postMessage(texts); }
oc中经过config接收消息,须要实现WKScriptMessageHandler这个协议
//js调用oc -(void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{ if ([message.name isEqualToString:@"shareList"]) { NSLog(@"%@",message.body); } }
2.2oc向js发消息
大体仍是仍是经过evaluateJavaScript这个方法,可是细节发生了变化
-(IBAction)dadaClick:(id)sender{ NSString *js = [NSString stringWithFormat:@"wkAsyncAlert('%@')",@"wkwebview"]; [_wkWebView evaluateJavaScript:js completionHandler:^(id _Nullable ret, NSError * _Nullable error) { //ret为js执行的返回结果 NSLog(@"ret:%@",ret); //error为js执行出错时的反馈 NSLog(@"err:%@",error); }]; }
2.3js调用alert等ui事件时,须要实现WKUIDelegate的方法,不然没有效果,例如
//js调用alert -(void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{ NSLog(@"message:%@",message); completionHandler();//必需调用,表示操做完成 }