序言
由于UIWebview即將廢棄,相比較于WKWebview枕扫,通過測試即可發(fā)現(xiàn)UIWebview占用更多內(nèi)存陪腌,且內(nèi)存很夸張。WKWebView網(wǎng)頁加載速度也有提升烟瞧,但是并不像內(nèi)存那樣提升那么多诗鸭。下面列舉一些其它的優(yōu)勢:
- 更多的支持HTML5的特性
- 官方宣稱的高達(dá)60fps的滾動(dòng)刷新率以及內(nèi)置手勢
- Safari相同的JavaScript引擎
- 將UIWebViewDelegate與UIWebView拆分成了14類與3個(gè)協(xié)議(官方文檔說明)
- 另外用的比較多的,增加加載進(jìn)度屬性:estimatedProgress
本文主要以WKWebview交互為主介紹参滴。分為三部分:1强岸、JS與OC交互 2、js事件注入 3砾赔、修改js系統(tǒng)或者自定義方法實(shí)現(xiàn)
一蝌箍、JS與OC交互
-
MessageHandle交互通過
- 1.1 創(chuàng)建WKWebViewConfiguration對象,配置各個(gè)API對應(yīng)的MessageHandler暴心。
#pragma mark -- 初始化
- (void)initView{
WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
WKPreferences *preference = [WKPreferences new];
preference.javaScriptCanOpenWindowsAutomatically = YES;
preference.minimumFontSize = 40.0;
configuration.preferences = preference;
// WKWebView
CGRect webViewFrame = CGRectMake(0, 180, self.view.bounds.size.width, self.view.bounds.size.height * 0.8);
self.webView = [[WKWebView alloc] initWithFrame:webViewFrame configuration:configuration];
NSString *urlStr = [[NSBundle mainBundle] pathForResource:@"index.html" ofType:nil];
NSURL *fileURL = [NSURL fileURLWithPath:urlStr];
[self.webView loadFileURL:fileURL allowingReadAccessToURL:fileURL];
self.webView.navigationDelegate = self;
self.webView.UIDelegate = self;
[self.view addSubview:self.webView];
[self addJSActionByOC];
}
- 配置MessageHandler
需要注意的是addScriptMessageHandler很容易引起循環(huán)引用妓盲,導(dǎo)致控制器無法被釋放,所以需要移除MessageHandler
#pragma mark -- 生命周期
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
// addScriptMessageHandler 很容易導(dǎo)致循環(huán)引用
// 控制器 強(qiáng)引用了WKWebView,WKWebView copy(強(qiáng)引用了)configuration专普, configuration copy (強(qiáng)引用了)userContentController
// userContentController 強(qiáng)引用了 self (控制器)
// js調(diào)用oc方之前要進(jìn)行注冊
[self.webView.configuration.userContentController addScriptMessageHandler:self name:@"Location"];
[self.webView.configuration.userContentController addScriptMessageHandler:self name:@"Share"];
[self.webView.configuration.userContentController addScriptMessageHandler:self name:@"Color"];
[self.webView.configuration.userContentController addScriptMessageHandler:self name:@"GoBack"];
[self.webView.configuration.userContentController addScriptMessageHandler:self name:@"ocZRAction"];
[self.webView.configuration.userContentController addScriptMessageHandler:self name:@"asyncAction"];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
// 因此這里要記得移除handlers
[self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"Location"];
[self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"Share"];
[self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"Color"];
[self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"GoBack"];
[self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"ocZRAction"];
[self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"asyncAction"];
}
- 1.2 實(shí)現(xiàn)協(xié)議方法
這實(shí)現(xiàn)三個(gè)協(xié)議<WKNavigationDelegate,WKUIDelegate, WKScriptMessageHandler>
WKUIDelegate
是因?yàn)槲以贘S中彈出了alert 悯衬。 -
js代碼
<input type="button" value="oc攔截alert提示" onclick="colorClick()" />
function colorClick() {
alert('55555')
}
-
oc代碼,js alert(),會觸發(fā)WKUIDelegate代理中的webView:runJavaScriptAlertPanelWithMessage:方法執(zhí)行
#pragma mark - WKUIDelegate
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提醒" message:message preferredStyle:UIAlertControllerStyleAlert];
[alert addAction:[UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
completionHandler();
}]];
[self presentViewController:alert animated:YES completion:nil];
}
WKScriptMessageHandler是因?yàn)槲覀円幚鞪S調(diào)用OC方法的請求。
WKScriptMessage有兩個(gè)關(guān)鍵屬性name 和 body脆诉。
因?yàn)槲覀兘o每一個(gè)OC 方法取了一個(gè)name甚亭,那么我們就可以根據(jù)name 來區(qū)分執(zhí)行不同的方法。body 中存著JS 要給OC 傳的參數(shù)击胜。
-
js代碼
<input type="button" value="調(diào)用oc方法傳遞事件" onclick="goBack()" />
function goBack() {
window.webkit.messageHandlers.asyncAction.postMessage("傳遞數(shù)據(jù)");
}
-
oc代碼
#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
// message.body -- Allowed types are NSNumber, NSString, NSDate, NSArray,NSDictionary, and NSNull.
if ([message.name isEqualToString:@"Location"]) {
} else if ([message.name isEqualToString:@"Share"]) {
} else if ([message.name isEqualToString:@"Color"]) {
}else if ([message.name isEqualToString:@"GoBack"]) {
}else if ([message.name isEqualToString:@"asyncAction"]) {
NSLog(@"假死頁面回調(diào)事件");
}else if ([message.name isEqualToString:@"ocZRAction"]){
NSLog(@"oc注入方法亏狰,調(diào)用oc事件 message = %@",message.body);
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提醒" message:@"調(diào)用成功" preferredStyle:UIAlertControllerStyleAlert];
[alert addAction:[UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
}]];
[self presentViewController:alert animated:YES completion:nil];
}
}
二、JS事件注入
-
js代碼
ocAddAction方法在js文件中并沒有定義
<input type="button" value="oc注入js事件,調(diào)用oc" onclick="ocAddAction()" />
-
OC注入代碼
實(shí)現(xiàn)WKNavigationDelegate協(xié)議方法偶摔,執(zhí)行之后會在WKScriptMessageHandler代理方法中攔截到ocZRAction
#pragma mark - WKNavigationDelegate
///加載完成網(wǎng)頁的時(shí)候才開始注入JS代碼,要不然還沒加載完時(shí)就可以點(diǎn)擊了,就不能調(diào)用我們的代碼了!
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
NSString *jsCode = @"function ocAddAction(a,b,c){\
window.webkit.messageHandlers.ocZRAction.postMessage('js注入')\
}";
[self.webView evaluateJavaScript:jsCode completionHandler:^(id _Nullable obj, NSError * _Nullable error) {
}];
}
三暇唾、動(dòng)態(tài)修改JS系統(tǒng)函數(shù)或者自定義函數(shù)實(shí)現(xiàn)
-
oc代碼
動(dòng)態(tài)修改alert系統(tǒng)函數(shù)的實(shí)現(xiàn),當(dāng)js中調(diào)用alert函數(shù)時(shí)辰斋,觸發(fā)的是我們自定義方法
#pragma mark -- 通過js注入策州,修改js內(nèi)部函數(shù)或者系統(tǒng)函數(shù)內(nèi)部實(shí)現(xiàn)
- (void)addJSActionByOC{
NSString *jsCode = @"alert = (function (oriAlertFunc){ \
return function(task)\
{\
window.webkit.messageHandlers.ocZRAction.postMessage(task);\
oriAlertFunc.call(alert,task);\
}\
})(alert);";
//injected the method when H5 starts to create the DOM tree
[self.webView.configuration.userContentController addUserScript:[[WKUserScript alloc] initWithSource:jsCode injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:YES]];
}
-
js代碼
<input type="button" value="獲取定位" onclick="locationClick()" />
function locationClick() {
alert('4444')
}