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();//必需調用,表示操做完成 }